Octave/Matlab Tutorial - Uni-freiburg.de

3y ago
45 Views
7 Downloads
1.99 MB
111 Pages
Last View : 17d ago
Last Download : 3m ago
Upload by : Ronnie Bonney
Transcription

Octave/Matlab TutorialKai ArrasSocial Robotics Labv.1.0, koa, Oct 09

Contents OverviewStart, quit, getting helpVariables and data typesMatricesPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibroboticsOctaveMatlab

OverviewOctave is the "open-source Matlab"Octave is a great gnuplot wrapper www.octave.org www.mathworks.comOctave and Matlab are both, high-level languages andmathematical programming environments for: Visualization Programming, algorithm development Numerical computation: linear algebra, optimization,control, statistics, signal and image processing, etc.Beware: Octave/Matlab programs can be slow.

OverviewMatlab-Octave comparison: Matlab is more flexible/advanced/powerful/costly Octave is for free (GPL license) There are minor differences in syntaxThis tutorial: This tutorial applies to Octave *and* Matlabunless stated otherwise!Current versions (autumn 2009): Octave 3.2.3 Matlab 7.6

Contents OverviewStart, quit, getting helpVariables and data typesMatricesPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibrobotics

Start, Quit, Getting Help To start Octave type the shell command octave,double-click Octave.app or whatever your OSneeds.You should see the prompt:octave:1 If you get into trouble, you can interrupt Octaveby typing Ctrl-C. To exit Octave, type quit or exit.

Start, Quit, Getting Help To get help, type help or doc To get help on a specific command ( built-infunction), type help command Examples: help size, help plot, help figure,help inv, . To get help on the help system, type help help Type q to exit help mode (alike man pages)

Start, Quit, Getting Help In the help text of Matlab functions, function namesand variables are in capital letters. Don't get confused! The (case-sensitive) namingconvention specifies lowercase letters for built-incommands. It is just a way to highlight text. Example: help round returnsROUNDRound towards nearest integer.ROUND(X) rounds the elements of X to the nearestintegers.See also floor, ceil, fix.[.] Octave texts are mixed, in lower- and uppercase.

Contents OverviewStart, quit, getting helpVariables and data typesMatricesPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibrobotics

Variables and Data Types Matrices (real and complex) Strings (matrices of characters) Structures Vectors? It's a matrix with one column/row Scalars? It's a matrix of dimension 1x1 Integers? It's a double (you never have to worry) Boolean? It's an integer (non-null true, 0 false)Almost everything is a matrix!Matlab has more types, e.g. OO-classes

Variables and Data TypesCreating a Matrix Simply type:octave:1 A [8, 2, 1; 3, -1, 4; 7, 6, -5]Octave will respond with a matrix in pretty-print:A 8213-1476-5 More on matrices, further down this tutorial.

Variables and Data TypesCreating a Character String Simply type:octave:4 str 'Hello World'Opposed to Matlab, Octave can also deal with doublequotes. For compatibility reasons, use single quotes.Creating a Structure Type for instance:octave:5 data.id 3;octave:6 data.timestamp 1265.5983;octave:7 data.name 'sensor 1 front';

Variables and Data TypesCreating a Array of Structures Oh, a new measurement arrives. Extend struct by:octave:8 data(2).id 4;octave:9 data(2).timestamp 1268.9613;octave. data(2).name 'sensor 1 front';Octave will respond with:data {1x2 struct array containing the fields:idtimestampname}

Variables and Data TypesDisplay Variables Simply type its name:octave:1 aa 4Suppress Output Add a semicolon:octave:2 a;octave:3 sin(phi);Applies also to function calls.

Variables and Data Types Variables have no permanent type.s 3 followed by s 'octave' is fine Use who (or the more detailed whos ) to list thecurrently defined variables. Example output:Variables in the current scope:Attr Name AaanssvSize 3x31x121x11x51x21Bytes 728168524Class doubledoubledoublechardouble

Variables and Data TypesNumerical PrecisionVariables are stored as double precision numbers inIEEE floating point format. realminSmallest positive floating pointnumber: 2.23e-308 realmaxLargest positive floating pointnumber: 1.80e 308 epsRelative precision: 2.22e-16

Variables and Data TypesControl Display of Float Variables format shortFixed point format with 5 digitsformat longFixed point format with 15 digitsformat short eFloating point format, 5 digitsformat long eFloating point format, 15 digitsformat short gBest of fixed or floating pointwith 5 digits (good choice) format long gBest of fixed or floating pointwith 15 digitsSee help format for more information

Variables and Data TypesTalking about Float Variables. ceil(x)Round to smallest integernot less than x floor(x)Round to largest integernot greater than x round(x) fix(x)Round towards nearest integerRound towards zeroIf x is a matrix, the functions are applied to eachelement of x.

Contents OverviewStart, quit, getting helpVariables and data typesMatricesPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibrobotics

MatricesCreating a Matrix Simply type:octave:1 A [8, 2, 1; 3, -1, 4; 7, 6, -5] To delimit columns, use comma or space To delimit rows, use semicolonThe following expressions are equivalent:A [8 2 1;3 -1 4;7 6 -5]A [8,2,1;3,-1,4;7,6,-5]

MatricesCreating a Matrix Octave will respond with a matrix in pretty-print:A 8372-1614-5 Alternative Example:octave:2 phi pi/3;octave:3 R [cos(phi) -sin(phi); sin(phi) cos(phi)]R 0.500000.86603-0.866030.50000

MatricesCreating a Matrix from Matricesoctave:1 A [1 1 1; 2 2 2]; Column-wiseoctave:2 C [A B]C 1212123333 Row-wise:octave:3 D [A; [44 44 44]]D 124412441244B [33; 33];

MatricesIndexingAlways "row before column"! aij A(i,j)Get an elementr A(i,:)Get a rowc A(:,j)Get a columnB A(i:k,j:l)Get a submatrix Useful indexing command end :octave:1 data [4 -1 35 9 11 -2];octave:2 v data(3:end)v 35 9 11 -2

MatricesColon ':', two meanings: Wildcard to select entire matrix row or columnA(3,:), B(:,5) Defines a range in expressions likeindices 1:5Returns row vector 1,2,3,4,5steps 1:3:61Returns row vector 1,4,7,.,61t 0:0.01:1Returns vector 0,0.01,0.02,.,1startincrementstop Useful command to define ranges: linspace

MatricesAssigning a Row/Column All referenced elements are set to the scalar value.octave:1 A [1 2 3 4 5; 2 2 2 2 2; 3 3 3 3 3];octave:2 A(3,:) -3;Adding a Row/Column If the referenced row/colum doesn't exist, it's added.octave:3 A(4,:) 4A 12-3422-3432-3442-3452-34

MatricesDeleting a Row/Column Assigning an empty matrix [] deletes thereferenced rows or columns. Examples:octave:4 A(2,:) []A 1-342-343-344-345-34octave:4 A(:,1:2:5) []A 22-3442-34

MatricesGet Size nr size(A,1)Get number of rows of Anc size(A,2)Get number of columns of A[nr nc] size(A)Get both (remember order)l length(A)Get whatever is biggernumel(A)Get number of elements in Aisempty(A)Check if A is empty matrix []Octave only: nr rows(A) nc columns(A)Get number of rows of AGet number of columns of A

MatricesMatrix Operations B 3*AMultiply by scalarC A*B X - DAdd and multiplyB A'Transpose AB inv(A)Invert As v'*Q*vMix vectors and matrices d det(A) [v lambda] eig(A) [U S V] svd(A) many many more.Determinant of AEigenvalue decompositionSing. value decomposition

MatricesVector OperationsWith x being a column vector s x'*x X x*x' e x*xInner product, result is a scalarOuter product, result is a matrixGives an errorElement-Wise Operations (for vectors/matrices) s x. xElement-wise additionp x.*xElement-wise multiplicationq x./xElement-wise divisione x. 3Element-wise power operator

MatricesUseful Vector Functions sum(v) cumsum(v) prod(v) cumprod(v)Compute sum of elements of vCompute cumulative sum ofelements of vCompute product of elements of vCompute cumulative product ofelements of v diff(v)Compute difference of subsequentelements [v(2)-v(1) v(3)-v(2) .] mean(v) std(v)Mean value of elements in vStandard deviation of elements

MatricesUseful Vector Functions min(v) max(v)Return smallest element in vReturn largest element in v sort(v,'ascend') Sort in ascending order sort(v,'descend') Sort in descending order find(v)Return vector of indices of all nonzero elements in v. Great in combination with vectorized conditions.Example:ivec find(datavec 5).

MatricesSpecial Matrices A zeros(m,n)Zero matrix of size m x nB ones(m,n)Matrix of size m x n with all 1'sI eye(n)Identity matrix of size nD diag([a b c]) Diagonal matrix of size 3 x 3with a,b,c in the maindiagonalJust for fun M magic(n)Magic square matrix of sizen x n. (All rows and columnssum up to the same number)

MatricesRandom Matrices and Vectors R rand(m,n)Matrix with m x n uniformlydistributed random numbersfrom interval [0.1] N randn(m,n)Row vector with m x n normallydistributed random numberswith zero mean, unit variance v randperm(n)Row vector with a randompermutation of the numbers1 to n

MatricesMulti-Dimensional MatricesMatrices can have more than two dimensions. Create a 3-dimensional matrix by typing, e.g.,octave:1 A ones(2,5,2)Octave will respond byA ans(:,:,1) 1111111111ans(:,:,2) 1111111111

MatricesMulti-Dimensional Matrices All operations to create, index, add, assign,delete and get size apply in the same fashionExamples: [m n l] size(A)A rand(m,n,l)m min(min(min(A)))aijk A(i,j,k)A(:,:,5) -3

MatricesMatrix Massage reshape(A,m,n)Change size of matrix A tohave dimension m x n. Anerror results if A does nothave m x n elements circshift(A,[m n]) Shift elements of A m timesin row dimension and ntimes in column dimension shiftdim(A,n)Shift the dimension of A by n.Generalizes transpose formulti-dimensional matrices

MatricesMatrix Massage ExampleLet P [x1; y1; x2; y2; .] be a 2nx1 column vectorof n (x,y)-pairs. Make it a column vector of(x,y,theta)-tuples with all theta values being pi/2: Make it a 2xn matrixoctave:1 P reshape(P,2,numel(P)/2); Add a third row, assign pi/2octave:2 P(3,:) pi/2; Reshape it to be a 3nx1 column vectoroctave:3 P reshape(P,numel(P),1);

StringsMost Often Used Commands strcatConcatenate stringsint2strConvert integer to a stringnum2strConvert numbers to a stringsprintfWrite formatted data to a string.Same as C/C fprintf for strings. Examples strcat('At step ',int2str(k),', p ',num2str(p,4))Given that strings are matrices of chars, this is alsos ['At step ' int2str(k) ', p ' num2str(p,4)]Octave responds withs At step 56, p 0.142

StringsOctave/Matlab has virtually all common string andparsing functions. You are encouraged to browse through the list ofcommands or simply type help command :strcmp, strncmp, strmatch, char, ischar,findstr, strfind, str2double, str2num,num2str, strvcat, strtrim, strtok, upper,lower,and many more.

Contents OverviewStart, quit, getting helpVariables and data typesMatricesPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibrobotics

PlottingPlotting in 2D plot(x,cos(x)) Display x,y-plotCreates automatically a figure window. Octave usesgnuplot to handle graphics. figure(n)Create figure window 'n'If the figure window already exists, brings it into theforeground ( makes it the current figure) figureCreate new figure window withidentifier incremented by 1.

PlottingSeveral Plots Series of x,y-patterns: plot(x1,y1,x2,y2,.)e.g. plot(x,cos(x),x,sin(x),x,x. 2) Add legend to plot: command legendlegend('cos(x)','sin(x)','x 2') Alternatively, hold on does the same job:octave:1 hold on; plot(x,cos(x));octave:2 plot(x,sin(x));octave:3 plot(x,x. 2);

PlottingFrequent Commands clf hold onClear figureHold axes. Don't replace plot withnew plot, superimpose plots grid on grid offAdd grid lines title('Exp1') xlabel('time') ylabel('prob')Set title of figure window subplotPut several plot axes into figureRemove grid linesSet label of x-axisSet label of y-axis

PlottingControlling Axes axis equalSet equal scales for x-/y-axesaxis squareForce a square aspect ratioaxis tightSet axes to the limits of the dataa axisReturn current axis limits[xmin xmax ymin ymax] axis([-1 1 2 5]) Set axis limits (freeze axes) axis offTurn off tic marks box on box offAdds a box to the current axesRemoves box

PlottingChoosing Symbols and Colors In plot(x,cos(x),'r ') the format expression'r ' means red cross. There are a number of line styles and colors,see help plot.Example:octave:1 x linspace(0,2*pi,100);octave:2 plot(x,cos(x),'r ',x,sin(x),'bx');produces this plot:

Plottingplot(x,cos(x),'r ',x,sin(x),'bx');

Plotting Adjusting the axesoctave:3 axis([0 2*pi -1 1])(try also axis tight ) Adding a legend, labels and a titleoctave:4 tave:5 title('Trigonometric Functions')octave:6 xlabel('x')octave:7 ylabel('y')

Plotting*)*) Title and x-labelwrongly cut off.This seems to be aOctave-AquaTermon Mac problem.Should work ingeneral.plot(x,cos(x),'r ',x,sin(x),'bx');

PlottingUhm., don't like it. New try:octave:1 clf; Controlling Color and Marker Sizeoctave:2 plot(x,cos(x),'r ',x,sin(x),'-x',.'Color',[1 .4 .8],'MarkerSize',2)octave:3 axis tight Adding Textoctave:4 text(1,-0.5,'cos(\phi)')octave:5 text(3,0.5,'sin(\phi)')Note the LateX syntax!

Plottingplot(x,cos(x),'r ',x,sin(x),'-x','Color',[1 .4 .8],'MarkerSize',2)

PlottingYepp, I like it. Get hardcopy!Exporting Figures print –deps myPicBW.eps print –depsc myPic.eps print –djpeg –r80 myPic.jpg print –dpng –r100 myPic.pngExport B/W .eps fileExport color .eps fileExport .jpg in 80 ppiExport .png in 100 ppiSee help print for more devices includingspecialized ones for Latex. print can also be called as a function. Then, ittakes arguments and options as a comma-separated list. E.g.: print('-dpng','-r100','myPic.png');

PlottingThis tutorial cannot cover the huge variety ofgraphics commands in Octave/Matlab. You are encouraged to browse through the list ofcommands or simply type help command :hist, bar, pie, area, fill, contour, quiver,scatter, compass, rose, semilogx, loglog,stem, stairs, image, imagescand many more.

PlottingPlotting in 3D plot3 mesh surfPlot lines and points in 3d3D mesh surface plot3D colored surface plotMost 2d plot commands have a 3D sibling. Checkout, for example,bar3, pie3, fill3, contour3, quiver3,scatter3, stem3

Contents OverviewStart, quit, getting helpVariables and data typesMatricesPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibrobotics

ProgrammingProgramming in Octave/Matlab is Super Easy.However, keep the following facts in mind: Indices start with 1 !!!octave:1 v 1:10octave:2 v(0)error: subscript indices must be either positiveintegers or logicals. Octave/Matlab is case-sensitive.Text Editors Use an editor with m-file syntax highlighting/coloring.

ProgrammingControl Structures if Statementif condition,then-body;elseif condition,elseif-body;elseelse-body;endThe else and elseif clauses are optional.Any number of elseif clauses may exist.

ProgrammingControl Structures switch Statementswitch expressioncase labelcommand-list;case labelcommand-list;.otherwisecommand-list;endAny number of case labels are possible.

ProgrammingControl Structures while Statementwhile condition,body;end for statementfor var expression,body;end

ProgrammingInterrupting and Continuing Loops breakJumps out of the innermost for or while loop thatencloses it. continueUsed only inside for or while loops. It skips overthe rest of the loop body, causing the next cycle tobegin. Use with care.

ProgrammingIncrement Operators (Octave only!)Increment operators increase or decrease the value ofa variable by 1. i Increment scalar i by 1 i--Decrement scalar i by 1 A Increment all elements of matrix A by 1 v--Decrement all elements of vector v by 1There are the C/C equivalent operators i , --A .

ProgrammingComparison Operators All of comparison operators return a value of 1 ifthe comparison is true, or 0 if it is false.Examples: i 6, cond1 (d theta) For the matrix-to-matrix case, the comparison ismade on an element-by-element basis. Example:[1 2; 3 4] [1 3; 2 4] returns [1 0; 0 1] For the matrix-to-scalar case, the scalar iscompared to each element in turn. Example:[1 2; 3 4] 2returns [0 1; 0 0]

ProgrammingComparison Operators any(v)Returns 1 if any element ofvector v is non-zero (e.g. 1) all(v)Returns 1 if all elements invector v are non-zero (e.g. 1)For matrices, any and all return a row vector withelements corresponding to the columns of the matrix. any(any(C))Returns 1 if any element ofmatrix C is non-zero (e.g. 1) all(all(C))Returns 1 if all elements inmatrix C are non-zero (e.g. 1)

ProgrammingRelational Operators x yTrue if x is less than y x yTrue if x is less than or equal to y x yTrue if x is equal to y x yTrue if x is greater than or equal to y x yTrue if x is greater than y x yTrue if x is not equal to y x ! yTrue if x is not equal to y (Octave only) x yTrue if x is not equal to y (Octave only)

ProgrammingBoolean Expressions B1 & B2Element-wise logical and B1 B2Element-wise logical or BElement-wise logical not !BElement-wise logical not (Octave only)Short-circuit operations: evaluate expression onlyas long as needed (more efficient). B1 && B2Short-circuit logical and B1 B2Short-circuit logical or

ProgrammingRecommended Naming Conventions Underscore-separated or lowercase notation forfunctionsExamples: intersect line circle.m,drawrobot.m, calcprobability.m UpperCamelCase for scriptsExamples: LocalizeRobot.m, MatchScan.m Note: Matlab/Octave commands are all inlowercase notation (no underscores or dashes)Examples: continue, int2str, isnumeric

Contents OverviewStart, quit, getting helpVariables and data typesMatrix arithmeticPlottingProgrammingFunctions and scriptsFiles I/OMiscOctave and Matlab in practicelibrobotics

Functions and ScriptsFunctionsComplicated Octave/Matlab programs can often besimplified by defining functions. Functions aretypically defined in external files, and can be calledjust like built-in functions. In its simplest form, the definition of a functionnamed name looks like this:function namebodyend Get used to the principle to define one functionper file (text files called m-file or .m-file)

Functions and ScriptsPassing Parameters to/from Functions Simply writefunction [ret-var] name(arg-list)bodyend arg-list is a comma-separated list ofinput arguments arg1, arg2, ., argn ret-var is a comma-separated list ofoutput arguments. Note that ret-var is a vectorenclosed in square brackets [arg1, arg2, ., argm].

Functions and ScriptsExample Functions:function [mu sigma] calcmoments(data)mu mean(data);sigma std(data);endfunction [haspeaks i] findfirstpeak(data, thresh)indices find(data thresh);if isempty(indices),haspeaks 0; i [];elsehaspeaks 1; i indices(1);endend

Functions and ScriptsLocal Variables, Variable Number of Arguments Of course, all variables defined within the body ofthe function are local variables. vararginCollects all input argument in a cellarray. Get them with varargin{i} varargoutCollects all output argument in a cellarray. Get them with varargout{i} nargin nargoutGet the number of input args.Get the number of output args.See help varargin, help varargout for details.

Functions and ScriptsFunctions and their m-File

Overview Octave is the "open-source Matlab" Octave is a great gnuplot wrapper www.octave.org www.mathworks.com Octave and Matlab are both, high-level languages and mathematical programming environments for: Visualization Programming, algorithm development Numerical computation: linear algebra, optimization, .

Related Documents:

Blade Runner Classic Uncommon flooring - Common standards Solerunner Uni Solerunner Bladerunner Solerunner Uni Uni ICE Uni SKY Uni SAND Uni EARTH Uni NIGHT Uni POOL Uni MOSS Uni PINE Sky Sky UNI Sky STONE ENDURANCE VISION SPLASH Ice Ice UNI Ice STONE Ice ENDURANCE Ice SPL

programming in Octave or MATLAB. The students are expected to work through all of those sections. Then they should be prepared to use Octave and MATLAB for their projects. The second chapter consists of applications of MATLAB/Octave. In each section the question or problem is formulated and the

FreeMat, Octave, Scilab Freemat, Octave, and SciLab are open source, Matlab-like variants Octave contains fewer features, but very similar syntax, and runs most Matlab scripts without modification. – Visualization is via gnuplot Scilab has a Matlab-like look and feel.

\A free numerical environment mostly compatible with Matlab" \free" \libero" 6 \gratis" What is compatibility? A point of much debate . If it works in Matlab, it should work in Octave. If it breaks it is considered a bug. If it works in Octave, it can break in Matlab. cdf, jgh GNU Octave A free high-level tool for Scienti c Computing 5/38

MATLAB tutorial . School of Engineering . Brown University . To prepare for HW1, do sections 1-11.6 – you can do the rest later as needed . 1. What is MATLAB 2. Starting MATLAB 3. Basic MATLAB windows 4. Using the MATLAB command window 5. MATLAB help 6. MATLAB ‘Live Scripts’ (for algebra, plotting, calculus, and solving differential .

MATLAB tutorial . School of Engineering . Brown University . To prepare for HW1, do sections 1-11.6 – you can do the rest later as needed . 1. What is MATLAB 2. Starting MATLAB 3. Basic MATLAB windows 4. Using the MATLAB command window 5. MATLAB help 6. MATLAB ‘Live Scripts’ (for

M. Roth J. Timmer Center for Data Analysis and Modelling, University of Freiburg, Freiburg, Germany M. Roth Kiepenheuer Institute for Solar Physics, University of Freiburg, Freiburg, Germany 123 Exp

An Introduction to Random Field Theory Matthew Brett , Will Penny †and Stefan Kiebel MRC Cognition and Brain Sciences Unit, Cambridge UK; † Functional Imaging Laboratory, Institute of Neurology, London, UK. March 4, 2003 1 Introduction This chapter is an introduction to the multiple comparison problem in func-