Basic Octave Commands

Song Jiaming | 31 Oct 2017

Responsive image

Octave is a mathematical programming language. It is a good alternative to Matlab.
In this blog, I will list down some basic but useful commands of it.

0. Global Operations

Description Commands Example/Remark
Show >> PS1(‘>>’) -
Help help eye Get description for eye function
Show path pwd where you currently at
Show files ls list all directories in this file
Move to a file cd ‘File Path Go to the destinated directory
Load data file load xxx.dat == load(‘xxx.dat’) -
Show varables who varaibles I have in current scope
Show varables 2 whos view more details
User input input(‘’); name=input(‘SJM’);
Clear clear -
Save save hello.mat v Save v into hello.mat (binary format)
Save 2 save hello.txt v -ascii human readable file


1. Basic Operations

Description Commands Example/Remark
Power ^ x^2
Comment % -
Equal == 1==2
Not equal ~= 1~=2
And && -
Or || -
XOR xor(m,n) xor(1,0)=1, xor(1,1)=0
Supress output ; a=3; No output will be shown
String ’’ b = ‘hi’
Pi pi pi
Print disp(a) -
Printf   disp(sprintf(‘2 decimals: %0.2f’,a))
Format format long/short How many digits to display
Histogram hist(w) Histogram
Histogram 2 hist(w,n) hist(randn(10000,1),30) (30 columns)


2. Create Data

Description Commands Example/Remark
Row Vector [ ] [ 1 2 3 ]
Column vector [;] [1;2;3]
Matrix [space and ;] A = [1 2;3 4;5 6]
Sequence start:step:stop 1:0.1:2 (2 is included)
Matrix of 1 ones(m,n) ones(2,3)
Matrix of 0 zeros(m,n) zeros(2,3)
Random number rand(m,n) rand(2,3)
Random number 2 rand(m,n) values follows Gaussian Distribution
Identity matrix eye(n) eye(4)
Magic matrix magic(n) nxn matrix with the same row/column/diag sum
Lower Triangular tril(A) make A lower triangular
Upper Triangular triu(A) make A upper triangular


3. Manipulate Data

Description Commands Example/Remark
Size size(A) A: Matrix
Num of rows size(A,1) 1st dimension of A
Num of columns size(A,2) 2nd dimmension of A
Length length(v) length of vector v
Get an element A(m,n) element at row m col n
Get a row A(m,:) all element along mth row
Get a column A(:,n) all element along nth column
Get rows A([1 3],:) all element from 1st and 3rd row
Append column A = [A,[1;2;3]] Append col at the end of A
Flattern A(:) put A into a single verctor(column by column)
Concatenate [A B] concatenate A and B
Concatenate 2 [A;B] put B below A
Get part of array v(1:10) first 10 element of v


4. Compute Data

Description Commands Example/Remark
Multiplication * A*B
Multiply piecewisely .* A.*B
Divide piecewisely ./ 1./v
Log log(v) -
Exponential exp(v) -
Absolute abs(v)  
Transpose A’
Max of vector max(v) v is a vector
Max and its index [val, ind] = max(v) val=max(v), ind = index of val
Max of matrix max(A) max of each col of A
Filter a vector with a critera v < n if (the entry of v) < n, return 1, else 0
Filter a vector 2 find(v < n) show index of entries in v which are less than n
Filter a matrix with a critera [r,c]=find(A>=n) r=row index, c=col index, of the entry in A that is > n
Sum sum(v) sum of all entries in v
Sum by column sum(A,1) each column sum up of A
Sum by row sum(A,2) each row sum up of A
Product prod(v) product of all entries in v
Floor floor(v) floor of all entries
Ceiling ceil(v) ceiling of all entries
Max between 2 matrices max(A,B) take max of entry of A,B
Column-wise max max(A,[],1) column wise maximum of A
Row-wise max max(A,[],2) row wise maximum of A
Max of matrix max(max(A)) -
Flipping flipud(A) 1230->0321
Pseudo inverse pinv(A) -


5. Plot Data

5.1. Plot in the same figure:

Let y1 = sin(t),y2 = cos(t)

  1. plot a graph of y1 against t: plot(t,y1)
  2. then plot the 2nd graph with red color:
    • hold on
    • plot(t, y2, 'r')
  3. set axis scale, x in [x1,x2] and y in [y1,y2]: axis[x1,x2. y1,y2]
  4. label axis:
    • xlabel('time')
    • ylabel('value')
  5. label graphs:
    • legend('sin', 'cos')
  6. figure title: title('my plot')
  7. save this figure: print -dpng 'myPlot.png'
  8. Close this figure: close
  9. If you want to leave the window on but close the figure: clf

5.2. Show figures separately:

  1. figure(1); plot(t, y1)
  2. figure(2); plot(t, y2)

5.3. Subplots

  • Divede plot a m x n grid: subplot(m,n)
  • Divede plot a m x n grid and access ith subplot: subplot(m,n,i)

5.4. Visualise a matrix

  • Visualise A: imagesc(A)
  • Show the colour scale and set theme colour:
    • imagesc(A), colourbar, colormap gray;
    • use ‘,’: separete 3 commands (but write in 1 line)
    • use ‘;’ separate 3 commands but doesn’t show their results


6. Loop

6.1 For Loop

for i = 1:10,
    v(i) = 2^i;
end;

Or,

indices = 1:10
for i=indices,
    disp(i)
end;

6.2 While Loop

i=1;
while i<=5,
    v(i) =100;
    i=i+1;
end;

Or,

while true,
    v(i) = 999;
    I = i+1;
    if i==6,
        break;
    end;
end;


7. If-Else Statement

if v(1) ==1,
   statement;
elseif v(1) ==2,
   disp();
else
  statement;
end;


8. Code in a file

Below, nameOfFunction is the function name, x is the parameter.
This function returns y.

  1. In the Scipt,
    function y = nameOfFunction(x)
    y=x^2;
    end
    
  2. Then go to the directory:
    Enter: nameOfFunction(2) => ans = 4

Note: Let twoValues() be a function which returns 2 values [c,d]
Then [a,b] = twoValues() gives a=c and b=d.



References

  1. Octave/Matlab Tutorial, Andrew Ng