GNU Octave

From NoskeWiki
Jump to: navigation, search

About

GNU Octave is a high-level programming language, primarily intended for numerical computations, and very useful for matrix operations. It provides its own command line interface for solving linear and nonlinear problems and plotting graphs. The language is very similar to and *mostly* comaptible with MATLAB - but unlike Matlab is free and open source under a GNU General Public License.

This page is my own "cheat sheet" where I list out most of the commands I'll need. Most of them I actually saw in an excellent online machine learning course which is referenced and acknowledged properly below, and was my reason for learning Octave. Octave is an excellent language to prototype machine learning.

Installing Octave

You will need the free download here. It works on all platforms, although on windows you will need to install it with Cygwin.


Octave Commands

Here I go through some commands - roughly in the order I saw them in the online machine learning course. Often I'll explain output in the % comments, but generally I have saved space by not showing any output lines. If you install Octave you can copy and paste these commands to see the full output from each line.

A few important things to note:

  • "%" - denotes line comments.
  • ";" - put this on the end of a line to suppress output, otherwise "v = [1:100]" will show all 100 lines with .
  • "a=1,b=2,c=3" - comma chain commands... and can change , to ; to suppress output.
  • "cd ls pwd" - these common unix commands work as you'd expect.
  • you can write code in files ending with ".m" (example: myFunction.m) and call those files / functions so long as you are in that directory.

The Basics

LONG_OCTAVE_PROMPT> PS1('>> ');   % Give you nicer prompt.
>> format long;                   % Format long or short for future output.
 
>> A = [1 2; 3 4; 4 6];     % Will create 3x2 matrix (3 rows, 2 cols) 
>> vec = [1;2;3;4]          % Makes vector (4 cols, 1 row)
>> vec = [1:0.2:2]          % Equivalent to [1; 1.2; 1.4; 1.6; 1.8; 2]
>> i = eye(6)               % 6x6 identity matrix (0s with 1s down diagonal)
>> M = ones(1,2)            % 2x1 matrix will all ones
>> M = zeros(100,2)         % 100x2 matrix will all ones
>> M = rand(2,3)            % 2x3 matrix with random values between 0 and 1
>> M = randn(2,3)           % Gausian random values 
 
>> W = -6 + sqrt(16)*(randn(1,1000))  % Creates 1x1000 matrix of 0-1 values
                                      % Then multiplies by 4 and subtracts 6
                                      % From all values.
>> hist(W,50)    % Shows histogram of above vector with 50 bins.
 
>> help hist     % Show help on any command.
>> help help     % General help.


Loading and Saving Data to Files

>> cd 'C:\Users\anoske\Desktop\'
>> ls                       % Shows I have 'featuresX.dat' on my desktop.
>> load('featuresX.dat')    % Loads space separated matrix into 'featuresX'.
>> who                      % Print out all variables which exist.
>> whos                     % As above, also shows me size of 'featuresX'.
>> length(featureX)         % Prints max dimension of featureX.
>> m = size(A);             % Prints "3 2" - 1x2 matrix showing A's dimensions.
>> m = size(featureX,1)     % m set to number of rows in featuresX (2=#rows).
 
>> v = featuresX(1:10,:)    % Put first 10 rows of featureX into V.
>> clear featuresX          % Clear this variable.
>> save hello world.txt v -ascii   % Saves v as text (ASCII).


Matrix and Vector Manipulation

>> single_val = A(3,2);     % Will return 3rd row of 2nd column (4).
>> A(:,2)                   % Get all in 2nd column.
>> A = (A,[100,101,102])    % Appends another col vector (3 rows) on right.
>> A(:)                     % Put all values into single column (3x3 > 9x1).
>> A = [A B]                % Concatenate B on right (must be same #rows).
>> A = [A;B]                % Concatenate B below (must be same # cols).


Computation on Matrixes

>> v = [1, 2, 3]               % NOTE: commas behave same as semicolons
>> A = [1 2; 3 4; 5 6]         %
>> B = [11 12; 13 14; 15 16]   % -- Set some examples we will use
>> C = [1 1; 2 2]              %
 
>> A * C       % matrix multiplication (results is 3x2 matrix)
>> A .* B      % element-wise multiplication (must be same dimensions)
>> A .^ 2      % " " " " " "  square   > [1, 4, 9]
>> 1 ./ v      % " " " " " "  inverse
>> log(v)      % " " " " " "  log
>> exp(v)      % " " " " " "  base e exponentiaion [e^1; e^2; e^3]
>> abs([-1, 2, -3])          % Make all positive
>> -v                        % Same as "-1 * v".
>> v + ones(length(v), 1)    % Same as "1 + v".
 
>> a = [1; 2; 14; 0.5]
>> val = max[a]         % Returns (3) max value in v.
                         %   WARNING: if matrix does max for each column.
>> [val.ind] = max(A)   % Returns: val = 14, ind = 3.
>> a < 3                % Returns: [1 1 0 1]    (element-wise compare).
 
>> A'                   % A transpose   > [1 3 5; 2 4 6].
>> A = magic(3)         % 3x3 matrix where all cols up to same value.
                         % ... in this case 9 (see "help magic").
>> r,c = find(A>=7)     % Finds the row, column index of all values >= 7.
                         % Where: c = col, r = row of any value >= 7.
>> sum(a)               % Adds all elements in a and returns (17.5).
>> sum(A,1)             % Sum each row (1=row) in A.
>> sum(sum(A))          % Sums all elements in A and would return (27).
>> ceil(a)              % Round up all values in a.
>> floor(a)             % Round down all values in a.
>> max(max(A))          % Would return 9.


Plotting Graphs

>> % DISPLAY A NICE SIN PLOT:
>> t = [1;0.01;1];
>> y1 = sin(2*pi*4*t];
>> plot(t,y1);           % Show nice sin curve in default blue.
 
>> % DRAW SIN AND COS CURVE ON SAME GRAPH:
>> y2 = cos(2*pi*4*t];
>> plot(t,y1);
>> hold on;              % Says to wait with plot instead of overwriting
>> plot(t,y2,'r');       % Add to graph with cos plot in red
>> xlabel('time');          %
>> ylabel('value');         % -- Add labels, legend and title
>> legend('sin','cos');     %
>> title('My Plot');    %
>> print -dpng 'myPlot.png';  % Saves plot to PNG
>> close;                     % Close plot
 
>> % DRAW CURVES IN DIFFERENT WINDOWS:
>> figure(1); plot(t,y1);
>> figure(2); plot(t,y2);
>> axis([0.5 1 -1 1]);     % Scale display
>> clf;                    % Clear plot
 
>> % DRAW TWO PLOTS IN SAME WINDOW:
>> subplot(1,2,1); plot(t,y1);   % Divides plot into 1x2 grid
>> subplot(1,2,2); plot(t,y2);   % ... and puts the side-by-side
 
>> % COLORSQUARES / HEATMAP PLOT:
>> A = magic(5)
>> imagesc(A);                            % Shows colored squares of 5x5 matrix
>> imagesc(A), color bar, colormap gray,  % Nice gray heat map with bar on side


Control Statements

>> % FOR LOOPS:
>> v = zeros(5,1)
 
>> for i=1:5,
>>   v(i) = 2^i;
>> end;            % Will set values to [2; 4; 8; 16; 32].
 
>> indicies = 1:5;
>> for indicies,
>>   disp(i);
>> end;            % Will display above values.
 
>> % WHILE LOOPS:
>> i = 1;
>> while i <= 3,
>>   v(i) = 100;
>>   i = i+1;      % Overwrites first 3 vals [100; 100; 100; 16; 32].
>> end;            
 
>> i = 1;
>> while i true,
>>   v(i) = 999;
>>   i = i+1;
>>   if i==4,
>>     break;      % Overwrites first 4 vals [999; 999; 999; 999; 32]
>>   end;
>> endl;
 
>> % IF STATEMENTS:
>> if v(1) == 1,
>>   disp('value is one');
>> elseif v(1) == 999,
>>   disp('value is 999');
>> else,
>>   disp('value is something else');
>> end;


Functions

A function can be written very easily and usually in relatively few lines of code, as in this first example:

>> function y = squareThisNumber(x)                   % Says it will return y.
>> y = x ^ 2;

Importantly, functions are usually written in .m files with the same name. Lets say we add to our desktop a file "squareAndCubeThisNumber.m" with this content:

function [y1 y2] = squareAndCubeThisNumber(x)
y1 = x^2;
y2 = x^3;

Now we can run:

>> cd "C:\Users\anoske\Desktop"
>> [a,b] = squareAndCubeThisNumber(5);   % Finds our file and returns: a = 25, b = 125.


Links


Acknowledgements: Professor Andrew Ng at Stanford who runs an online "Machine Learning" course. Andrew's videos elegantly taught me the basics of Octave, and is the main basis of this article to date. Jeremy from Google from encouraging me to take this course.