This is a mix of lecture notes which are mostly based on the course materials from Coursera - https://class.coursera.org/matlab-002/, and own experience as well.
The URLs have tended to be invalidated over the years. So, please look for materials: Mike Fitzpatrick , Comuter Programming with MATLAB.
I did experiments on MATLAB R2015a, 2020. The material in the amount presented in the course is quite enough to use Matlab to the full needs of passing courses in the past.
The difference with the Coursera class is that this Material presented in this note is augmenting by comparing Matlab with Python, C++, and sometimes
with Perl.
Last Update of the Note: 1-SEP-2020
Matlab was born to eliminate the amount of painful work with Fortran.
The main goal of Matlab was to solve numerical problems on a computer.
It was born in 1970 due to the efforts of Professor Cleve Moler at the University of Nex Mexico.
The names of modules with functions are named - * .m (but called as modules).
Module names with starting code also have the extension - * .m (but called as scripts)
To run scripts from the cmd line prompt, you just need to write the name of the script and that's it.
To import functions from other modules, you do not need to write any import directives, as it is done in Python (import) and in Perl (use)
Variable name maximum of 63 characters
It seems like there is no support for a full IntelliSense (auto add-on) at least in MatLab 2015 version, although there is some kind of auto-completion by TAB.
1. To refer to the elements of a matrix, you should use notation with square brackets [], but with parentheses (), and list indices should be separated by commas
2. Strings must be enclosed in single quotes, double quotes are not supported at all at least in Matlab 2015, but it's not true for Matlab 2020. The last one support both type of quotes.
3. Comments start with percent sign % and end with end-of-line
4. Comments starting with %% are surrounded by a section. The sections are special in that they can be run separately with the Run section button.
5. The operator not equal is written as "~ ="
1. Built-in debugger
2. Support for binary operations on matrices with elementwise operations
3. Documentation is written in the body of the function in <eol>, comments-documentation, <eol>
4. The big button Publish => publish creates an HTML report on the executed script via taking into account the conceptual division of the script body into sections and plot graphs.
5. Most (if not all) functions work with both scalars and vectors of values
function [tbl summa] = testMe (n, m) % Some Function descript whcih can be called % commands etc .... tbl = 1 summa = n+m end
[a, b] = testMe(11,2)
In the text below I used angle brackets to make an accent into operator naming.
Vector
Vector column
Empty vector
Matrices definition and access to it
Work with random numbers
Matrix. tricks.
Functions in Matlab
Export functions from * .m
Persistent value
Strings
Structs
Pointers
x = [1,3,10]; y = [2 5 8]; x(4) = 12 y = [y 10]
x = [1;3;10];
x = []
1. matrices are entered row by row, the transition to a new row of the matrix is performed through the operator <;>
x = [0 1 -1; 2.5 12 100];
2. access to the element of the matrix:
x(1,2) - the first row, the second column.
3. indexing occurs with "1" for rows and columns of the matrix. For indexing vectors, the initial index is also 1.
4. Functions for working with matrices
This function can be used for memory preallocation: zeros (), ones ()
rand (3,4) - create a 3x4 matrix filled with random numbers, with uniform distribution in [0,1]
randi (10,3,5) - create a 3x5 matrix filled with random integers from 1 to 10 with uniform distribution
randn (1, 100) - construct a vector with normal distribution
rng (0) - reset the software pseudo-random generator to the state it was before starting Matlab
rng ('shuffle') - get a really random sequence based on the system timer.
1. Some of the matrix elements can be filled with values using the operator <:>
x = [1: 4; 1 22 33 44];
2. It is possible not to initialize the matrix in advance, but use the operator equal to write some values in X(i, j) even outside the allowable dimension.
This is prohibited in C++, but for Matlab, the matrix will optionally be expanded to the minimum size such that the entered element will be included in the matrix. The rest of the added elements are initialized to zero.
x(10,9) = 12;
However, it is impossible to read without an appropriate shape initialization.
3. You can write/read not only one variable but several at once
x = [1: 3; 4: 6]; display (x); x (1, [2,3]) = 100; display (x); y = [1: 3; 4: 6]; display (y ([1,2], 3)); display (y ([1,2], [3,1,2]));
4. You can duplicate numbers in line numbers as well as use the syntax with a colon to select
x = [1: 3; 4: 6; 7: 9]; display (x (1: 3, [1,2,3,3]))
5. The last index when referring to a line, the column can be replaced with the keyword end .
x = [1: end; 4: 6; 7: 9];
display (x (1: end, [1,2,3,3]));
6. Expression 1: end has the same meaning as ":", as in Python for vectors in which it performs complete slicing.
7. Matrices can be combined into a block matrix
x = [[1: 3; 4: 6], [1: 3; 4: 6]]
8. Matrix transposition is performed using the <'> operator
x = [[1: 3; 4: 6]]'
9. To transpose a vector, you need to use parentheses or square brackets before applying the transpose operation '
(1:4)'
10. The componentwise multiplication of matrices is performed by the operator <.*>
X .* Y
11. Matrix multiplication (which is the usual multiplication of a matrix <m, n> * <n, p>) is written as
x * y
12. When performing a binary operation on a matrix and a scalar the scalar is expanded into a matrix of the appropriate size and the binary operation is performed componentwise.
13. When ":" is passed to the matrix during indexing, the matrix is interpreted as a one-dimensional column vector.
This column vector is constructed by concatenating matrix column by column
x = [1: 3; 4: 6]
x (:)
14. Converting a vector to a matrix (useful when saving to a binary file)
a = [1 2 3 4 5 6]; dims = [2 3]; reshape (a, dims)
repmat ([1 2 3], 3,2)
ans =
1 2 3 1 2 3
1 2 3 1 2 3
1 2 3 1 2 3
% import numpy as np; np.tile(np.arange(1,4), (3,2))
% Analog for numpy, a popular numeric library for Python
reshape ([1 2 3 4 5 6], [3 2])
ans =
1 4
2 5
3 6
% import numpy as np; np.arange(1,7).reshape ((3, 2))
% Analog for numpy, a popular numeric library for Python
Like C++ (and to some extent as in Python) local variables are stored only in the context of a function.
Function with no arguments
Function with arguments and a single return value
% Function without arguments.
% Declare that result will be in rr
function rr = myRand
rr = 1 + rand (3,4);
end
% The body of the function is enclosed between function / end, there is no return statement in Matlab
% Function with args
% Declare that result will be in rr
function rr = myRand (low, high)
rr = low + rand (3,4) * (high-low);
end
Function with arguments and "more than one "output
% Function with args
% Declare that result will be in rr
function [rnd, summ] = myRand (low, high)
rnd = low + rand (3,4) * (high-low);
summ = sum (rnd (:));
end
[x ss] = myRand (1, 2);
Check that the function exists and see its type:
exist myRand
This is an analog of defined in Perl
Overload via nargin, nargout
Matlab supports some form of function overloading. Implementable for your own function too.
Idea - if necessary, using built-in variables, by which you can find out the number of elements in the input and output.
Using nargin, you should initialize uninitialized variables. Write the required variables through nargout.
function [tbl summa] = testMe (n, m)
% built-in variable number of arguments
if nargin <2
m = n;
end
% Outter matrix multiplication
tbl = (1: n) '* (1: m);
% built-in variable number of output arguments
if nargout == 2
summa = sum (tbl (:));
end
end
* .m exports only the first function from the module, the rest remain local to the module.
The name of this function must match the name of the * .m file without extension.
% myRand.m file
% Function with args. this function can be called from outside
function [rnd, s] = myRand (low, high)
rnd = low + rand (3,4) * (high-low);
s = sumAll (rnd);
end
% Subfunction with args, available only in this module
function sm = sumAll (x)
sm = sum (x (:));
end
These are variables within a function that persist internally between intermediate values of the function, much like static in C
persistent x;
Perform initial initialization using isempty () checking for an empty 0-by-0 matrix.
function a = testMe ()
persistent x;
if isempty (x)
x = 0;
end
x = x + 1;
a = x;
end
If you want to reset persistent variables, then you need to call from outside clear with the name of the function.
clear testMe
There are strings in Matlab that store chars of the ASCII type
a = 'qwerty';
length (a);
b = a (2);
a (3) = '!';
display (a);
% Convert to an array of chars
double(a)
% String replace
strrep('a b c', 'b', 'replace')
Creation of a structure and immediately filling in its key, value.
a = struct ('a', 123, 'b', 456)
After that similar to Python, it's possible to append argument just via explicit writing to attributes that did not exist before writing.
a.c = 1
There is limited support, they are called cells.
They are really needed while storing an array of strings. Suitable for storing objects of different types in an array.
b{1} = 123; % Create 1x1 cell
b{2} = '123'; % Create 1x1 cell
a = {1,2};
for = i 1: length (a)
end
m = cell (2,3); % Create 2x3 cell
global x;
help exist; help ('exists');
<x = 1, y = 1;>
1 + 2i (matlab)
1 + 2j (python)
a = [] a = [a 1]; (matlab)
a = []; a = a + [1]; (python)
x = [1,2,3,4]; x (x> 2);
(Matlab)
x = [1,2,3,4];
[i for i in x if (i> 2)]
(python)
x = -1: 3
x (logical (x))
( Matlab )
x = range (-1,4);
[i for i in x if (i! = 0)]
( python )
x = -1: 3; x (x> 1) = x (x> 1) + 100
(Matlab)
class (12.0) (matlab)
type (12.0) (python)
Python
class Empty: pass
a = Empty ()
aa = 1
a.b = 1
Matlab
a.a = 1
a.b = 1
Matlab (alternative)
a=struct
a.a = 1
a.b = 1
Declare a variable in a function that is global, not local
View help for exist command. Similar to Python's help(command)
Same as <x, y = 1,1;> Identical construct is available in Python.
In Python for this construct, the boxing/unboxing of the value occurs.
In Python, as in Matlab, a complex type variable is built into the language, unlike C ++.
Complex types as I know are represented there as elements of the standard library
Append value to the vector
Vector filtering - only obtain items from the vector which satisfies the constraint.
In the version for Matlab, not only scalar 2 can be used, but also a vector of values of a suitable size for pairwise comparison.
In Matlab terms, it is called logical indexing
In Python terms, it is called list comprehensions
If it is necessary to read the elements of a matrix for this operation, the matrix is converted into a vector with a column-major order.
If it is necessary to write, then the target matrix is not converted into a vector, but viewing the elements of the matrix is like occurs in column-major order.
Set (update) values of part of vector elements
View variable type
The creation of a structure does not require a prior declaration of the structure type. In Matlab, you don't even need to write a = Empty ()
Extra functions for working with structures:
Conditions are written in python style, but
no colons in if, else, elif statements like in python
elseif (Matlab) is written instead of elif (python)
end (Matlab) is put at the end of the if block
function testMe (x)
if x == 0
fprintf ('Hello x == 0 \ n');
elseif x <-1
fprintf ('Hello x <-1 \ n');
elseif x> 1
fprintf ('Hello x> 1 \ n');
else
fprintf ('Hello x in [-1, 1] \ n');
end ;
return;
end
For loops in Matlab are simple and not as sophisticated as in C ++.
% semicolon is optional at the end of for statement
for n = 1: 5
fprintf ('% d \ n', n);
end
xVec = 0: 0.1: 1;
% in the rhs can be any expression
for x = xVec
fprintf ('% f \ n', x);
end
A = [1: 4; 5: 8];
R = [];
[row col] = size (A);
for r = 1: row
for c = 1: col
R (r, c) = A (r, c) * A (r, c);
fprintf ('access (% d% d) \ n', r, c);
end
end
display (A);
display (R);
For loops are easy to write but they have lacked the power of while loops. C++ do/while is not supported in Matlab even up 2020.
function y = approx_sqrt (x)
y = x;
while abs (y * y - x)> 1e-7 * x
y = (x / y + y) / 2;
end
end
The same keyword is supported in loops in Matlab similar to other languages: break, continue - just like in Python, C ++, C, C #, Java, etc.
help precedence
view priorities via the command prompt
Priority table
1. Matlab clamps the result of an expression if it falls out of scope.
2. It is possible to cast types through casting expression similar to C-cast. E.g. int8 (1.2)
Command in Matlab
pwd
cd
ls
save / load
save fname var1 var2 ...
load fname
[num,] [num, txt, raw] = xlsread ('filename.xlsx')
xlsread (fname, 1, 'D15') % Read file
xlsread (fname, 1, 'D15: E17')
% Get cells
% filename, sheetName | sheetNumber, and cell name
% There is exist xlswrite as well
Work with text files
fopen, fclose,
fprintf, fgets - for text
fwrite, fread - for binary files (opened without 'r' prefix)
Description
Current directory as in Linux (print working directory)
Change directory as in Linux
As in Linux
Save workspace to file / Load data from file to workspace
Save specific variables to a specific file
Download a specific workspace
num - matrix of doubles, smaller than a spreadsheet.
Matlab finds the min. rectangle to cover all numbers.
Cells with not-numeric data will be NaN (Not a number)
txt - similar to num, but contains all text
raw - the union of num and txt