Download presentation
Presentation is loading. Please wait.
1
A Quick Octave Tutorial 阮 翀 ruanchong_ruby@163.com
2
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.
3
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 ^
4
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 https://en.wikibooks.org/wiki/MATLAB_Programming/Differences_between_Octave_an d_MATLAB
5
Octave GUI Current directory Workspace Command window Command history
6
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!
7
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 to clear a variable. i.e. clear j
8
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.
9
Logical operators And: & or && (Octave only) Or: | or || (Octave only) Not: ~ or ! (Octave only)
10
The help Command Ask Octave itself if you wants to know about a command. Syntax: help
11
The doc Command Syntax: doc help shows comments in m-files, while doc shows corresponding documents, which is more detailed.
12
Matrices revisited All variables are matrices, including vectors and scalars. Recall:
13
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.
14
More on matrices One more example A(:) reshape A into a vector.
15
More on matrices Generating sequence Syntax : : and are included may be negative may be omitted (step=1 by default) The result is a row vector
16
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
17
More on matrices Concatenation Use repmat function Use ; and, (operate matrices as if they are scalars)
18
More on matrices Matrix operations vs. Element-wise operations + - * and.* ^ and.^
19
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()
20
More on matrices Note: Operations between scalar and a matrix is performed element by element.
21
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!
22
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.
23
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
24
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.
25
Elementary math functions (Cont’d) An example
26
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)
27
Graphics foundation 2D Plotting
28
Graphics foundation 3D Plotting
29
Importing/Exporting data Load and save load loads all variables from a file load loads only the variable x from the file save saves all workspace variables to a binary.mat file named filename.mat save saves variables x in filename.mat Note:.mat is the internal data format in Octave For more information, try help command
30
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
31
Importing/Exporting data Copy data from/to an excel sheet Use command xlsread and xlswrite
32
Control flow If clause >> if >> … >> elseif >> … >> else >> … >> end
33
Control flow Switch clause >> switch >> case >> … >> case >> … >> otherwise >> … >> end Unlike C, Octave doesn’t need BREAKs in each case.
34
Control flow For clause >> for = >> … >> end While clause >> while >> … >> end
35
Control flow Break & continue The same as C.
36
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
37
M-files M-scripts an external file that contains a sequence of Octave statements.
38
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
39
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.
40
M-files M-functions Syntax: >> function [o1, o2, …, on] = (i1, i2, …, in) >> % one line summary (optional, but recommended) >> % more detailed description (optional) >> … >> end % optional, but recommended >> % optional sub-functions go here. Use help to check your comment. When there are only one output value, the square bracket may be omitted. function o1= (i1, i2, …, in)
41
M-files M-functions
42
M-files M-functions default parameters Use nargin
43
M-files M-functions function handle Useful when you want to pass a function as a parameter Syntax: @ @(arglist) Use a function handle as a function!
44
M-files: a summary
45
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
46
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.
47
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.
48
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++!
49
The End Any questions? Thanks for your listening.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.