Programming WithMatlab Complete Lessons
Programming WithMatlab Complete Lessons
Programming WithMatlab Complete Lessons
by
by
Example—
A page with six rows
24 34 17 35
array
32 8 11 48
35 6 37 27
37 25 13 7
Array
◦ Any set of numbers arranged in a rectangular
pattern.
10 14 48 25
27 1 9 23
8 46 18 38
Three-dimensional
24 34 17 35
39 17 30 5
Example— 13 18 41
22
37
33 29 44
A stack of such 46 8 13 12
pages 42 10 29
32
19
8 11 48
7 39 33 45
13 13 27 28
35 6 37 27
28 16 34 8
40 31 45 4
37 25 13 7
24 26 37 41
12 24 15 3
Higher dimensions are uncommon
The most common have special names:
◦ 2D array = “matrix” (plural is “matrices”)
◦ 1D array = “vector”
Most ingenious part of Cleve Moler’s
invention of MATLAB was the way he set it up
to deal with matrices.
MATLAB stands for “Matrix Laboratory”!
>> X = [1:4; 5:8; 9:12];
1: 1 2 3 4
2: 5 6 7 8 rows
3: 9 10 11 12
>> X = [1:4; 5:8; 9:12];
1: 2: 3: 4:
1 2 3 4
5 6 7 8
9 10 11 12
columns
>> X = [1:4; 5:8; 9:12];
>> X(2,3)
3:
1 2 3 4
2: 5 6 7 8
9 10 11 12
>> ans =
7
Z = X + Y means
◦ Z(m,n) = X(m,n) + Y(m,n) for all valid m and n
Different from Array Multiplication!
Z = X * Y means that for all valid m and n
Precedence Table
x = a + b + c
x = a * b * c
◦ order does not matter with addition or multiplication
y = a ^(b ^ c) is not the same as
y = (a ^ b)^ c
In programming, the order in which operators
of the same precedence are executed is called
associativity
In MATLAB, it is left to right
y = a ^ b ^ c is the same as
y = (a ^ b) ^ c
Lesson 3: Functions
by
by
by
x == 2
block
control
statement
control
statement
x == 2
block
control
statement
control
statement
x == 2
block
Executing a different set of statements based
on the condition:
function guess_my_number(x)
if x == 2
fprintf('Congrats! You guessed my number!\n');
else
fprintf('Not right, but a good guess.\n');
end
control
statement
x == 2
block2
block1
control
statement
x == 2
block2
block1
control
statement
x == 2
block2
block1
if-statement:
if conditional
block
end
Produces a result that depends on the
relation between its two operands
It can appear outside if-statements!
Logical values:
◦ Non-zero: true
◦ Zero: false
◦ MATLAB returns 1 for true
How to combine logical values?
Logical operators:
not:
◦ flips the value of its (single) operand
and:
◦ true if and only if both of its operands are true
or:
◦ false if and only if both of its operands are false
false false
false true
true false
true true
not:
◦ flips the value of its (single) operand
and:
◦ true if and only if both of its operands are true
or:
◦ false if and only if both of its operands are false
>> help precedence
1. transpose (.'), power (.^), complex conjugate
transpose ('), matrix power (^)
2. unary plus (+), unary minus (-), logical negation (~)
3. multiplication (.*), right division (./), left
division (.\), matrix multiplication (*), matrix right
division (/), matrix left division (\)
4. addition (+), subtraction (-)
5. colon operator (:)
6. less than (<), less than or equal to (<=),
greater than(>), greater than or equal to (>=),
equal to (==), not equal to (~=)
7. element-wise logical AND (&)
8. element-wise logical OR (|)
9. short-circuit logical AND (&&)
10. short-circuit logical OR (||)
if-statements can contain other if-statements
Consider the example with a single if-elseif-
else statement:
function ultimate_question(x)
if x == 42
fprintf('Wow! You answered the question.\n');
elseif x < 42
fprintf('Too small. Try again.\n');
else
fprintf('Too big. Try again.\n');
end
Here is a version with nesting:
function ultimate_question_nested(x)
if x == 42
fprintf('Wow! You answered the question.\n');
else
if x < 42
fprintf('Too small. Try again.\n');
else
fprintf('Too big. Try again.\n');
end
end
Here is another version with nesting:
function ultimate_question_nested2(x)
if x <= 42
if x == 42
fprintf('Wow! You answered the question.\n');
else
fprintf('Too small. Try again.\n');
end
else
fprintf('Too big. Try again.\n');
end
Functions that behave differently based on
◦ Number of input or output arguments
◦ Type of input or output arguments
Many built-in functions are polymorphic
(sqrt, max, size, plot, etc.)
How do we make our functions
polymorphic?
Two built-in functions:
◦ nargin: returns the number of actual input
arguments that the function was called with
◦ nargout: returns the number of output arguments
that the function caller requested
function [table summa] = multable(n, m)
if nargin < 2
m = n;
end
if nargout == 2
summa = sum(table(:));
end
A function declaration specifies:
◦ Name of the function,
◦ Number of input arguments, and
◦ Number of output arguments
Function code and documentation specify:
◦ What the function does, and
◦ The type of the arguments
◦ What the arguments represent
Robustness
◦ A function is robust if it handles erroneous input and
output arguments, and
◦ Provides a meaningful error message
function [table summa] = multable(n, m)
if nargin < 1
error('must have at least one input argument');
end
if nargin < 2
m = n;
elseif ~isscalar(m) || m < 1 || m ~= fix(m)
error('m needs to be a positive integer');
end
if ~isscalar(n) || n < 1 || n ~= fix(n)
error('n needs to be a positive integer');
end
if nargout == 2
summa = sum(table(:));
end
Extra text that is not part of the code
MATLAB disregards it
Anything after a % is a comment until the end
of the line
Purpose:
◦ Extra information for human reader
◦ Explain important or complicated parts of the program
◦ Provide documentation of your functions
Comments right after the function declaration
are used by the built-in help function
function [table summa] = multable(n, m)
if nargin < 1
error('must have at least one input argument');
end
…
>> help multable
Variables:
◦ Local
◦ Global
◦ Persistent
Persistent variable:
◦ It’s a local variable, but its value persists from one
call of the function to the next.
◦ Relatively rarely used
◦ None of the bad side effects of global variables.
Lesson 6: Loops
by
Repeat for n = 1 to 5
Add n to total
Print total
Set total to 0
Set n to 1
Execute Add n to total (total equals 1)
Set total to 0
Set n to 2
Execute Add n to total (total equals 3)
Set n to 3 Repeat for n = 1 to 5
Execute Add n to total (total equals 6)
Add n to total
Set n to 4
Execute Add n to total (total equals 10)
Set n to 5
Print total
Execute Add n to total (total equals 15)
Print total
MATLAB implementation using a for-loop:
total = 0;
for n = 1:5
total = total + n;
end
fprintf('total equals %d\n',total);
total = 0;
for n = 1:5 control statement
loop total = total + n; body
end
fprintf('total equals %d\n',total);
Here is another example:
list = rand(1,5); % assigns a row vector of random numbers
for x = list
if x > 0.5
fprintf('Random number %f is large.\n',x)
else
fprintf('Random number %f is small.\n',x)
end
end
for x = rand(1,5)
if x > 0.5
fprintf('Random number %f is large.\n',x)
else
fprintf('Random number %f is small.\n',x)
end
end
The values assigned to the loop index do not
have to be
◦ integers,
◦ regularly spaced, or
◦ assigned in increasing order,
In fact, they do not have to be scalars either:
◦ The loop index will be assigned the columns of the array
Any other control construct can be used in the
body of the for-loop
◦ if-statements
◦ other loops
◦ etc.
for-loops work well when we know the
number of necessary iterations before
entering the loop
Consider this problem:
◦ Starting from 1, how many consecutive positive
integers do we need to add together to exceed 50?
◦ The only way to solve this with a for-loop is to guess
a large enough number for the number of iterations
and then use a break statement.
◦ There is a better solution: a while-loop!
function [n total] = possum(limit)
total = 0;
n = 0;
while total <= limit
n = n + 1;
total = total + n;
end
fprintf('sum: %d count: %d\n', total, n);
function [n total] = possum(limit)
total = 0;
n = 0;
while total <= limit
n = n + 1;
total = total + n;
end
fprintf('sum: %d count: %d\n', total, n);
>> possum(50)
sum: 55 count: 10
ans =
10
function [n total] = possum(limit)
total = 0;
n = 0;
while total <= limit control statement
n = n + 1;
loop body
total = total + n;
end
fprintf('sum: %d count: %d\n', total, n);
while conditional
block
end
if conditional
block
end
Difference:
while condition is evaluated repeatedly
block is executed repeatedly as long as condition is true
Problem: given a vector, v, of scalars, create a
second vector, w, that contains only the non-
negative elements of v
Traditional solution:
w = [];
jj = 0;
for ii = 1:length(v)
if v(ii) >= 0
jj = jj + 1;
w(jj) = v(ii);
end
end
MATLAB provides a more elegant solution:
w = [];
for ii = 1:length(v)
if v(ii) >= 0
w = [w v(ii)];
end
end
The ultimate solution needs only a single line:
by
function char_codes
for ii = 33:126
fprintf('%s',char(ii));
end
fprintf('\n');
An array must be homogeneous:
◦ It cannot contain elements of multiple types.
A struct can be heterogeneous:
◦ It can contain multiple types.
A struct is different from an array:
◦ fields, not elements
◦ field names, not indices
◦ Fields in the same struct can have different types.
Versatility inside:
◦ A field of a struct can contain another struct.
>> r.ssn = 12345678
r =
ssn: 12345678
>> class(r)
ans =
struct
>> class(r.ssn)
ans =
double
>> r.name = 'Homer Simpson'
r =
ssn: 12345678
name: 'Homer Simpson‘
>> r.address.street = '742 Evergreen Terrace'
r =
ssn: 12345678
name: 'Homer Simpson'
address: [1x1 struct]
An array must be homogeneous:
◦ It cannot contain elements of multiple types.
A struct can be heterogeneous:
◦ It can contain multiple types.
A struct is different from an array:
◦ fields, not elements
◦ field names, not indices
◦ Fields in the same struct can have different types.
Versatility inside:
◦ A field of a struct can contain another struct.
◦ Structs can hold arrays, and arrays can hold structs.
How to store a page of text?
◦ Each line should be a separate string
◦ Cannot use an array of chars:
Each line would have to have the same length
◦ A vector of objects with each referring to one line
Pointer
◦ Each variable (scalar, vector, array, etc.) is stored in
the computer memory.
◦ Each memory location has a unique address.
◦ A pointer is a variable that stores an address.
◦ MATLAB calls a pointer a “cell”.
MATLAB has a restrictive pointer model
◦ Strict rules on what can be done with cells
◦ Harder to make mistakes
But it is a powerful way to store
heterogeneous data
◦ Cell arrays
◦ Used more frequently than structs
New syntax:
◦ To access the data a cell points to, use: { }
>> p = cell(2,3)
p =
[] [] [] p
[] [] []
>>
[]
>> p = cell(2,3)
p =
[] [] [] p
[] [] []
>> p{2,1} = pi
p =
[] [] []
[3.14] [] []
>> 3.14
[]
>> p = cell(2,3)
p =
[] [] [] p
[] [] []
>> p{2,1} = pi -17
p =
[] [] []
[3.14] [] []
>> p{1,1} = int8(-17) 3.14
p =
[-17] [] []
[]
[3.14] [] []
>>
>> p = cell(2,3)
p =
[] [] [] p
[] [] []
>> p{2,1} = pi -17
p =
[] [] []
[3.14] [] []
>> p{1,1} = -17 3.14
p =
[-17] [] []
[]
[3.14] [] []
>> p{2,2} = 'Awesome'
P =
[-17] [] []
[3.14] 'Awesome'[] ‘A’ ‘w’ ‘e’ ‘s’ ‘o’ ‘m’ ‘e’
>> p{2,3} = [2 4; 6 8; 10 12]
P =
[-17] [] []
[3.14] ‘Awesome’[3x2 double] p
>> -17
2 4
3.14
6 8
[] 10 12
3.14
6 8
[] 10 12
3.14
6 8
[] 10 12
[] 10 12
>>
12
p
18 24
-17
2 4
3.14
6 8
[] 10 12
by
function write_array_bin(A,filename)
fid = fopen(filename,'w+');
if fid < 0
error('error opening file %s\n‘, filename);
end
fwrite(fid,A,'double');
fclose(fid);
Example: read a double array from a binary file
function A = read_bin_file(filename,data_type)
fid = fopen(filename,'r');
if fid < 0
error('error opening file %s\n',filename);
end
A = fread(fid,inf,data_type);
fclose(fid);