Octave Matlab Tutorial
Octave Matlab Tutorial
Kai Arras
Overview
Start, quit, getting help
Variables and data types
Matrices
Plotting
Programming
Functions and scripts
Files I/O Octave
Misc
Octave and Matlab in practice
librobotics
Matlab
Overview
Matlab-Octave comparison:
Matlab is more flexible/advanced/powerful/costly
Octave is for free (GPL license)
There are minor differences in syntax
This tutorial:
This tutorial applies to Octave *and* Matlab
unless stated otherwise!
Overview
Start, quit, getting help
Variables and data types
Matrices
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Start, Quit, Getting Help
octave:1>
Overview
Start, quit, getting help
Variables and data types
Matrices
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Variables and Data Types
Simply type:
octave:1> A = [8, 2, 1; 3, -1, 4; 7, 6, -5]
A =
8 2 1
3 -1 4
7 6 -5
Simply type:
octave:4> str = 'Hello World'
Creating a Structure
Suppress Output
Add a semicolon:
octave:2> a;
octave:3> sin(phi);
Overview
Start, quit, getting help
Variables and data types
Matrices
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Matrices
Creating a Matrix
Simply type:
octave:1> A = [8, 2, 1; 3, -1, 4; 7, 6, -5]
Alternative Example:
octave:2> phi = pi/3;
octave:3> R = [cos(phi) -sin(phi); sin(phi) cos(phi)]
R =
0.50000 -0.86603
0.86603 0.50000
Matrices
Creating a Matrix from Matrices
Column-wise
octave:2> C = [A B]
C =
1 1 1 33
2 2 2 33
Row-wise:
octave:3> D = [A; [44 44 44]]
D =
1 1 1
2 2 2
44 44 44
Matrices
Indexing
Always "row before column"!
aij = A(i,j) Get an element
r = A(i,:) Get a row
Get a column
c = A(:,j)
B = A(i:k,j:l) Get a submatrix
Adding a Row/Column
If the referenced row/colum doesn't exist, it's added.
octave:3> A(4,:) = 4
A =
1 2 3 4 5
2 2 2 2 2
-3 -3 -3 -3 -3
4 4 4 4 4
Matrices
Deleting a Row/Column
Assigning an empty matrix [] deletes the
referenced rows or columns. Examples:
octave:4> A(2,:) = []
A =
1 2 3 4 5
-3 -3 -3 -3 -3
4 4 4 4 4
octave:4> A(:,1:2:5) = []
A =
2 4
2 2
-3 -3
4 4
Matrices
Get Size
nr = size(A,1) Get number of rows of A
nc = size(A,2) Get number of columns of A
Get both (remember order)
[nr nc] = size(A)
l = length(A) Get whatever is bigger
numel(A) Get number of elements in A
isempty(A) Check if A is empty matrix []
Octave only:
nr = rows(A) Get number of rows of A
nc = columns(A) Get number of columns of A
Matrices
Matrix Operations
B = 3*A Multiply by scalar
C = A*B + X - D Add and multiply
Transpose A
B = A'
B = inv(A) Invert A
s = v'*Q*v Mix vectors and matrices
d = det(A) Determinant of A
[v lambda] = eig(A) Eigenvalue decomposition
[U S V] = svd(A)
Sing. value decomposition
ans(:,:,2) =
111 1 1
111 1 1
Matrices
Multi-Dimensional Matrices
All operations to create, index, add, assign,
delete and get size apply in the same fashion
Examples:
[m n l] = size(A)
A = rand(m,n,l)
m = min(min(min(A)))
aijk = A(i,j,k)
A(:,:,5) = -3
Matrices
Matrix Massage
reshape(A,m,n) Change size of matrix A to
have dimension m x n. An
error results if A does not
have m x n elements
Example
s = strcat('At step ',int2str(k),', p = ',num2str(p,4))
Overview
Start, quit, getting help
Variables and data types
Matrices
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Plotting
Plotting in 2D
plot(x,cos(x)) Display x,y-plot
Creates automatically a figure window. Octave uses
gnuplot to handle graphics.
Example:
octave:1> x = linspace(0,2*pi,100);
octave:2> plot(x,cos(x),'r+',x,sin(x),'bx');
plot(x,cos(x),'r+',x,sin(x),'bx');
Plotting
plot(x,cos(x),'r+',x,sin(x),'bx');
Plotting
Adding Text
octave:4> text(1,-0.5,'cos(\phi)')
octave:5> text(3,0.5,'sin(\phi)')
plot(x,cos(x),'r+',x,sin(x),'-x','Color',[1 .4 .8],'MarkerSize',2)
Plotting
Exporting Figures
print –deps myPicBW.eps Export B/W .eps file
print –depsc myPic.eps
print –djpeg –r80 myPic.jpg Export color .eps file
print –dpng –r100 myPic.png Export .jpg in 80 ppi
Export .png in 100 ppi
Overview
Start, quit, getting help
Variables and data types
Matrices
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Programming
Programming in Octave/Matlab is Super Easy.
However, keep the following facts in mind:
Octave/Matlab is case-sensitive.
Text Editors
if Statement
if condition,
then-body;
elseif condition,
elseif-body;
else
else-body;
end
switch Statement
switch expression
case label
command-list;
case label
command-list;
...
otherwise
command-list;
end
while Statement
while condition,
body;
end
for statement
break
Jumps out of the innermost for or while loop that
encloses it.
continue
Used only inside for or while loops. It skips over
the rest of the loop body, causing the next cycle to
begin. Use with care.
Programming
[1 2; 3 4] == [1 3; 2 4] returns [1 0; 0 1]
[1 2; 3 4] == 2 returns [0 1; 0 0]
Programming
Comparison Operators
Overview
Start, quit, getting help
Variables and data types
Matrix arithmetic
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Functions and Scripts
Functions
Simply write
function [ret-var] = name(arg-list)
body
end
function an = normangle(a,mina);
if a < Inf,
[...]
help text
Functions and Scripts
Setting Paths
Overview
Start, quit, getting help
Variables and data types
Matrix arithmetic
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Files I/O
Save Variables
After a complex of lengthy computation, it is recom-
mended to save variables on the disk.
save my_vars.mat
Saves all current variables into file my_vars.mat
load my_vars.mat
Retrieves all variables from the file my_vars.mat
load results.mat X Y
Retrieves only X and Y from the file results.mat
A = load('data.txt')
Files I/O
Open, Write, Close Files
fopen Open or create file for writing/reading
fclose Close file
fprintf
Write formatted data to file. C/C++
format syntax.
Example:
v = randn(1000,1);
fid = fopen('gauss.txt','w');
for i = 1:length(v),
fprintf(fid,'%7.4f\n',v(i));
end
fclose(fid);
Files I/O
Attention, Popular Bug
Read/write images
imread Read image from file (many formats)
imwrite Write image to file (many formats)
Contents
Overview
Start, quit, getting help
Variables and data types
Matrix arithmetic
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Misc
Cleaning Up
clear A Clear variable A
clear frame* Clear all variables whose names
start with frame...
clear Clear all variables
clear all Clear everything: variables,
globals, functions, links, etc.
Tab completion
Octave/Matlab have tab completion. Type some
letters followed by tab to get a list of all commands
that start with the letters you typed.
Misc
Built-in Unix Commands
pwd Display current working directory
ls List directory. See also dir .
Change directory
cd
mkdir Make new directory
rmdir Delete directory
Related Commands
movefile Move file
copyfile Copy file
Misc
Random Seeds
rand and randn obtain their initial seeds from the
system clock.
To generate identical/repeatable sequences, set the
random generator seeds manually.
Overview
Start, quit, getting help
Variables and data types
Matrix arithmetic
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
Octave/Matlab in Practice
Useful Stuff in Practice
Making animations
Calling unix/dos functions from within Octave
programs
Increasing speed
Octave/Matlab in Practice
Output Files in Octave Syntax
A = [
0.7922580.3258230.957683 0.647680 0.498282
0.3286790.4146150.270472 0.975753 0.043852
0.6018000.0629140.837494 0.621332 0.870605
0.9403640.0365130.843801 0.806506 0.804710
];
figure(1); clf; hold on;
plot(1:size(A,1),A(:,1));
A = load('data.txt');
[m n] = size(A);
figure(1);
for i = 1:n,
plot(1:m,A(:,i));
fname = sprintf('frames/frame%04d.png',i);
print('-dpng','-r100',fname);
end
A = load('data.txt');
[m n] = size(A);
figure(1);
for i = 1:n,
plot(1:m,A(:,i));
axis([1 m min(min(A)) max(max(A))]);
fname = sprintf('frames/frame%04d.png',i);
print('-dpng','-r100',fname);
end
Octave/Matlab in Practice
Calling unix/dos Functions
unix('ls -al')
unix('ftp < ftp_script')
unix('./myprogram')
sinphi = sin(phi);
for i = 1:100,
A(i,:) = rand(1,50);
end;
Write:
Structure of arrays
data.x = linspace(0,2*pi,100);
data.y = sin(data.x);
Array of structure
people(1).name = 'Polly J Harvey';
people(1).age = 32;
Overview
Start, quit, getting help
Variables and data types
Matrix arithmetic
Plotting
Programming
Functions and scripts
Files I/O
Misc
Octave and Matlab in practice
librobotics
librobotics
(directly: www.gnu.org/software/octave/doc/interpreter)
Kai Arras
Social Robotics Lab