a quick octave tutorial 阮 翀 [email protected]
TRANSCRIPT
A Quick Octave Tutorial阮 翀
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.
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 ^
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
Octave GUI
• Current directory• Workspace• Command window• Command history
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!
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
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.
Logical operators
• And: & or && (Octave only)• Or: | or || (Octave only)• Not: ~ or ! (Octave only)
The help Command
• Ask Octave itself if you wants to know about a command.• Syntax: help <command>
The doc Command
• Syntax: doc <command>• help shows comments in m-files, while doc shows corresponding
documents, which is more detailed.
Matrices revisited
• All variables are matrices, including vectors and scalars.• Recall:
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.
More on matrices
• One more example
• A(:) reshape A into a vector.
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
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
More on matrices
• Concatenation• Use repmat function• Use ; and , (operate matrices as if they are scalars)
More on matrices
• Matrix operations vs. Element-wise operations• +• -• * and .*• ^ and .^
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()
More on matrices
• Note: Operations between scalar and a matrix is performed element by element.
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!
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.
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
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.
Elementary math functions (Cont’d)
• An example
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)
Graphics foundation
• 2D Plotting
Graphics foundation
• 3D Plotting
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
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
Importing/Exporting data
• Copy data from/to an excel sheet• Use command xlsread and xlswrite
Control flow
• If clause• >> if <condition>• >> …• >> elseif <condition>• >> …• >> else• >> …• >> end
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.
Control flow
• For clause• >> for <variable> = <expression>• >> …• >> end
• While clause• >> while <condition>• >> …• >> end
Control flow
• Break & continue• The same as C.
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
M-files
• M-scripts• an external file that contains a sequence of Octave statements.
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
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.
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)
M-files
• M-functions
M-files
• M-functions• default parameters
• Use nargin
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!
M-files: a summary
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
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.
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.
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++!
The End
Any questions?
Thanks for your listening.