a quick octave tutorial 阮 翀 [email protected]

49
A Quick Octave Tutorial [email protected]

Upload: preston-wilcox

Post on 21-Jan-2016

286 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

A Quick Octave Tutorial阮 翀

[email protected]

Page 2: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

What is Octave?

• A high-level language, primarily intended for numerical computations.• Not a general purpose programming language!• Octave is interpreted, not compiled.• Optimized for matrix operations.

• An open source substitute of MATLAB(Matrix Laboratory)• Note: MATLAB is a commercial software.

• Most syntax are compatible with MATLAB.• Almost all MATLAB scripts can run in Octave.

Page 3: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Difference between Octave & Matlab• Octave absorbed some C-Style/Bash-like syntax• Continuous assignment.

• a = b = c = 1; % Octave only• [a, b, c] = deal(1); % Octave & MATLAB

• C-style autoincrement and assignment• i++; ++i; i+=1; % Octave only

• String delimiters: • Octave: ’ or ’’, while MATLAB requires ’

• Comment: • Octave: % or #, while MATLAB requires %

• Exponentiation: • Octave: ^ or **, while MATLAB requires ^

Page 4: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Difference between Octave & Matlab• End of blocks:

• Octave: end or endfor, endif, … , while MATLAB requires end

• Hexadecimal notation:• Octave: 0x7F, while MATLAB requires hex2dec(‘7F')

• Line Continuation:• Octave: …, \, or start a new line directly if the current expression is not closed.• MATLAB: … only.

• Logical operator NOT:• NOT (for a Boolean variable): ~ or !, while MATLAB requires ~• NOT-EQUAL: ~= or !=, while MATLAB requires ~=

• For more details, please refer to• https://en.wikibooks.org/wiki/MATLAB_Programming/Differences_between_Octave_an

d_MATLAB

Page 5: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Octave GUI

• Current directory• Workspace• Command window• Command history

Page 6: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Define variables

• Use semicolons(;) to suppress output.• Use square bracket([]) to denote vectors/matrices.• Use whitespaces or commas(,) to separate columns.• Use semicolons(;) to separate rows.• Use primes(’) to denote transpose.

• More about this later!

Page 7: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Predefine variables

• pi: 3.1415926…• eps: Smallest incremental number• NaN: Not a number, e.g. 0/0• inf: infinity• realmin, realmax: The smallest/largest usable positive real number• i and j: sqrt(-1)• Can be shaded by user defined variables!• Use clear <name> to clear a variable.• i.e. clear j

Page 8: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Relation Operators

• Less Than: <• Less Than or Equal: <=• Greater Than: >• Greater Than or Equal: >=• Equal To: ==• Not Equal To: ~= or != (Octave only)• Element-wise comparison is used for matrices and vectors.

Page 9: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Logical operators

• And: & or && (Octave only)• Or: | or || (Octave only)• Not: ~ or ! (Octave only)

Page 10: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

The help Command

• Ask Octave itself if you wants to know about a command.• Syntax: help <command>

Page 11: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

The doc Command

• Syntax: doc <command>• help shows comments in m-files, while doc shows corresponding

documents, which is more detailed.

Page 12: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Matrices revisited

• All variables are matrices, including vectors and scalars.• Recall:

Page 13: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Index• 1-indexed

• Indices starts from 1.• Column-major

• Elements are stored column by column.• Either 1-dim or 2-dim index is okay.

Page 14: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• One more example

• A(:) reshape A into a vector.

Page 15: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Generating sequence• Syntax

• <start>:<step>:<end>• <start> and <end> are included• <step> may be negative• <step> may be omitted (step=1 by default)• The result is a row vector

Page 16: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Slicing• A(idxSet1, idxSet2)• e.g.:

• A(1:2, 3:4)• A(3, 1:2)• A(2:end-1, 1)• A(:,3)

• Use end to denote the index of the last elements along some certain dimension• Use colon(:) to denote all possible indices along some dimension

Page 17: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Concatenation• Use repmat function• Use ; and , (operate matrices as if they are scalars)

Page 18: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Matrix operations vs. Element-wise operations• +• -• * and .*• ^ and .^

Page 19: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Matrix operations vs. Element-wise operations• / and ./

• A/B = A * inv(B)• \ and .\

• A\B = inv(A) * B

• Note: / and \ is much faster than inv()

Page 20: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• Note: Operations between scalar and a matrix is performed element by element.

Page 21: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices

• The size of a matrix can be modified when running• No index-out-of-bound error!

• Actually, the type of a variable could change!

Page 22: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More on matrices• Built-in Matrix Manipulation Function

• zeros : creates an array of all zeros, Ex: x = zeros(3,2)• ones : creates an array of all ones, Ex: x = ones(2)• eye : creates an identity matrix, Ex: x = eye(3)• rand : generates uniformly distributed random numbers in [0,1]• diag : Diagonal matrices and diagonal of a matrix• size : returns array dimensions• length : returns length of a vector (row or column)• det : Matrix determinant• inv : matrix inverse• eig : evaluates eigenvalues and eigenvectors• svd: singular value decompostion• rank : rank of a matrix• find : searches for the given values in an array/matrix.• norm : matrix/vector norms.

Page 23: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Elementary math functions

• abs - finds absolute value of all elements in the matrix• sign - signum function• sin,cos,… - Trignometric functions• asin,acos… - Inverse trignometric functions• exp - Exponential• log,log10 - natural logarithm, logarithm (base 10)• ceil,floor - round towards +infinity, -infinity respectively• round - round towards nearest integer• mod - modulo, the remainder of a divided by b.• real,imag - real and imaginary part of a complex matrix• These functions work element-wise when applied to matrices

Page 24: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Elementary math functions (Cont’d)

• sort - sort elements in ascending order and their indices• min, max – minimum/maximum value of an array and their indices• sum,prod - summation and product of elements• mean,median – average and median of arrays• std,var - standard deviation and variance

• Note: when applied to matrices more than one rows, these functions work column-wise unless other designated.

Page 25: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Elementary math functions (Cont’d)

• An example

Page 26: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Deal with multiple return values

• Functions are allowed to have multiple return values• Use ~ as a placeholder to filter out unwanted return values• Use [] to receive multiple return values (otherwise only the first one is kept)

Page 27: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Graphics foundation

• 2D Plotting

Page 28: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Graphics foundation

• 3D Plotting

Page 29: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Importing/Exporting data

• Load and save• load <filename>

• loads all variables from a file• load <filename> <x>

• loads only the variable x from the file• save <filename>

• saves all workspace variables to a binary .mat file named filename.mat• save <filename> <x>

• saves variables x in filename.mat• Note:

• .mat is the internal data format in Octave• For more information, try help command

Page 30: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Importing/Exporting data

• Read from/ Write to text files• fopen, fscanf, fwrite, fclose• Do not forget to close a file• Other useful functions

• fread, fprintf

Page 31: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Importing/Exporting data

• Copy data from/to an excel sheet• Use command xlsread and xlswrite

Page 32: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Control flow

• If clause• >> if <condition>• >> …• >> elseif <condition>• >> …• >> else• >> …• >> end

Page 33: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Control flow

• Switch clause• >> switch <switch_expr>• >> case <case_expr1>• >> …• >> case <case_expr2>• >> …• >> otherwise• >> …• >> end

• Unlike C, Octave doesn’t need BREAKs in each case.

Page 34: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Control flow

• For clause• >> for <variable> = <expression>• >> …• >> end

• While clause• >> while <condition>• >> …• >> end

Page 35: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Control flow

• Break & continue• The same as C.

Page 36: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-files are Octave source codes• Do not confuse with .mat file, which is used to store data (such as matrices)

• There are 2 types of M-files:• M-script• M-function

Page 37: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-scripts• an external file that contains a sequence of Octave statements.

Page 38: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-scripts• Side effects:

• Variables remain in the workspace after M-scripts is executed.• Variables already existing in the workspace may be overwritten.

• To list variables in the workspace, use whos command

Page 39: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-functions• accept arguments• produce one or more outputs• Filename should agree with function name• Sub-functions are allowed• No side effects: Each M-function has its own workspace, separated from the

Octave base workspace.

Page 40: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-functions• Syntax:

• >> function [o1, o2, …, on] = <function_name>(i1, i2, …, in)• >> % one line summary (optional, but recommended)• >> % more detailed description (optional)• >> …• >> end % optional, but recommended• >> % optional sub-functions go here.

• Use help <function_name> to check your comment.• When there are only one output value, the square bracket may be omitted.

• function o1= <function_name>(i1, i2, …, in)

Page 41: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-functions

Page 42: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-functions• default parameters

• Use nargin

Page 43: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files

• M-functions• function handle

• Useful when you want to pass a function as a parameter• Syntax:

• @<function_name>• @(arglist) <anonymous_function>

• Use a function handle as a function!

Page 44: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

M-files: a summary

Page 45: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Other useful functions

• bsxfun• Expand matrix virtually when necessary

• disp/display• Useful when debugging

• error• Syntax: error(‘some prompt here!’);• Print a prompt and quit

Page 46: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Efficient programming (important)

•Avoid using nested loops as far as possible• Try to replace nested loops with efficient matrix

manipulation, which is called vectorization.•Pre-allocate your arrays when possible•Use built-in functions as much as possible.

Page 47: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

Efficient programming (Cont’d)

• An example:• S(n) = 1^3 + 2^3 + … + n^3• Try to avoid loops, esp. nested loops.• Use built-in function will be much faster.

Page 48: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

More advice

• View Octave as a powerful calculator rather than an IDE• Use help/doc• Think in matrices/vectors:• In most cases, your function should work for both scalars, vectors and

matrices• Spare no effort in vectorizion• Nested loop could be 1000+X slower than C/C++!

Page 49: A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com

The End

Any questions?

Thanks for your listening.