Introduction To Matlab: Makhdoom Ibad Ullah Hashmi
Introduction To Matlab: Makhdoom Ibad Ullah Hashmi
Matlab construction
Core functionality as compiled C-code, m-files
Additional functionality in toolboxes (m-files)
Launch Pad
Command
Window
History
Matlab Desktop
Workspace
Command
Window
Current
DIrectory
Matlab Help
Matlab Editor
Color keyed
text with auto
indents
If a command is followed by a semicolon (;), result of the computation is not shown on the
command window
Data Types
All numbers are double precision
Text is stored as arrays of characters
You don’t have to declare the type of data (defined when running)
MATLAB is case-sensitive!!!
Data Types
Variables
MATLAB is case sensitive: “name”, “Name” and “NAME” are considered different variables
Never use a variable with the same name as a MATLAB command
Naming convention: use lowercase letters
Variables
Initialization using assignment statements
x=5
x=
5
y=x+1
y=
6
vector = [ 1 2 3 4 ]
vector =
1 2 3 4
matrix = [ 1 2 3; 4 5 6 ]
matrix =
1 2 3
4 5 6
matrix = [ 1 2 3; 4 5 ]
??? Error
a = [ 5 (2+4) ]
a=
5 6
Variables
t = zeros( size(z) )
t=
0 0 0
0 0 0
Matrices
1 2 5 2 5
1 0
1 0
1
C F
3 2 1 2 1
0 1 4 1 4
Matrices, Colon Operator
1 2 5
1 0
1 1 0 1
C E
3 2 1 3 2 1
0 1 4
Matrices, Colon Operator
1 2 5
1
0 1 3 2
C G
3 2 1 0 1
0 1 4
Matrices, Colon Operator
Variable_name = a:step:b
time = 0.0:0.5:2.5
time = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5]
Negative increment
values = 10:-1:2
values = [10, 9, 8, 7, 6, 5, 4, 3, 2]
Subarrays
y = [ 1 2 3; 4 5 6 ];
y(1,2)
ans =
2
y(2,1)
ans =
4
y(2)
ans =
4 (column major order)
Subarrays
y = [ 1 2 3; 4 5 6 ];
y(1,:)
ans = y(1,2:end)
1 2 3 ans =
y(:,2) 2 3
ans = y(:,2:end)
2 ans =
5 2 3
y(2,1:2) 5 6
ans =
4 5
Subarrays
x = [ -2 0 9 1 4 ];
x(2) = 5
x=
-2 5 9 1 4
x(4) = x(1)
x=
-2 5 9 -2 4
x(8) = -1
x=
-2 5 9 -2 4 0 0 -1
Subarrays
y = [ 1 2 3; 4 5 6 ];
y(1,2) = -5
y=
1 -5 3
4 5 6
y(2,1) = 0
y=
1 -5 3
0 5 6
y(1,2:end) = [ -1 9 ]
y=
1 -1 9
0 5 6
Subarrays
y = [ 1 2 3; 4 5 6; 7 8 9 ];
y(2:end,2:end) = 0
y=
1 2 3
4 0 0
7 0 0
y(2:end,2:end) = [ -1 5 ]
??? Error
y(2,[1 3]) = -2
y=
1 2 3
-2 0 -2
7 0 0
Special Values
pi: value up to 15 significant digits
i, j: sqrt(-1)
Inf: infinity (such as division by 0)
NaN: Not-a-Number (such as division of zero by zero)
clock: current date and time as a vector
date: current date as a string (e.g. 16-Feb-2004)
eps: epsilon
ans: default variable for answers
Displaying Data
The disp( array ) function
disp( 'Hello' );
Hello
disp(5);
5
disp( [ 'Bilkent ' 'University' ] );
Bilkent University
name = 'Selim'; disp( [ 'Hello ' name ] );
Hello Selim
Displaying Data
The num2str() and int2str() functions
d = [ num2str(16) '-Feb-' num2str(2004) ];
disp(d);
16-Feb-2004
x = 23.11;
disp( [ 'answer = ' num2str(x) ] );
answer = 23.11
disp( [ 'answer = ' int2str(x) ] );
answer = 23
Displaying Data
load filename
load filename.mat binary
load x.dat –ascii ascii
MATLAB Basics: Scalar Operations
variable_name = expression;
addition a+b a+b
subtraction a-b a-b
multiplication a x b a*b
division a/b a/b
exponent ab a^b
MATLAB Basics: Scalar Operations
x=3*2+6/2
x=?
Processing order of operations is important
parenthesis (starting from the innermost)
exponentials (left to right)
multiplications and divisions (left to right)
additions and subtractions (left to right)
x=3*2+6/2
x=9
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
+ Unary plus
- Unary minus
: Colon operator
' Transpose
* Matrix multiplication
^ Matrix power
Relational and Logical Operators
Operator Description
& Returns 1 for every element location that is true (nonzero) in both arrays, and 0 for all
other elements.
| Returns 1 for every element location that is true (nonzero) in either one or the other, or
both, arrays and 0 for all other elements.
~ Complements each element of input array, A.
== Equal to
~= Not equal to
Matrices
More commands:
Transpose B=A’
eye(n) -> returns an n X n identity matrix
Identity Matrix eye(m,n) -> returns an m X n matrix with ones on the main diagonal
and zeros elsewhere
Addition and Subtraction C =A +B C =A - B
factscript.m
%FACTSCRIPT – Compute n-factorial, n!=1*2*...*n
y = prod(1:n);
[output_arguments]= function_name(input_arguments)
% Comment lines
<function body>
factfun.m
function [z]=factfun(n)
% FACTFUN – Compute factorial
% Z=FACTFUN(N)
z = prod(1:n);
>> y=factfun(10);
Scripts or function: when use what?
Functions
Take inputs, generate outputs, have internal variables
Solve general problem for arbitrary parameters
Scripts
Operate on global workspace
Document work, design experiment or test
Solve a very specific problem once
facttest.m
% FACTTEST – Test factfun
N=50;
y=factfun(N);
Flow control - selection
if <logical expression>
<commands>
elseif <logical expression>
<commands>
else
<commands>
if height>170
end
disp(’tall’)
elseif height<150
disp(’small’)
else
disp(’average’)
end
Logical expressions
Relational operators (compare arrays of same sizes)
== (equal to) ~= (not equal)
< (less than) <= (less than or equal to)
> (greater than) >= (greater than or equal to)
Logical operators (combinations of relational operators)
& (and)
| (or)
~ (not)
Logical functions
xor
isempty
any if (x>=0) & (x<=10)
all disp(‘x is in range [0,10]’)
else
disp(‘x is out of range’)
end
Flow control repetition
for index=<vector>
<statements>
end
The <statements> are executed repeatedly.
At each iteration, the variable index is assigned
a new value from <vector>.
for k=1:12
kfac=prod(1:k);
disp([num2str(k),’ ‘,num2str(kfac)])
end
Example – selection and repetition
fact.m
function y=fact(n)
% FACT – Display factorials of integers 1..n
if nargin < 1
error(’No input argument assigned’)
elseif n < 0
error(’Input must be non-negative’)
elseif abs(n-round(n)) > eps
error(’Input must be an integer’)
end
for k=1:n
kfac=prod(1:k);
disp([num2str(k),’ ’,num2str(kfac)])
y(k)=kfac;
end;
Flow control – conditional repetition
while-loops
while <logical expression>
<statements>
end
k=1;
while prod(1:k)~=Inf,
k=k+1;
end
disp([‘Largest factorial in Matlab:’,num2str(k-1)]);
Programming tips and tricks
Programming style has huge influence on program speed!
tic;
slow.m fast.m
X=-250:0.1:250; tic
for ii=1:length(x) x=-250:0.1:250;
if x(ii)>=0, s=sqrt(x);
s(ii)=sqrt(x(ii)); s(x<0)=0;
else toc;
s(ii)=0;
end;
end;
toc