1
Outline:
What is Matlab?
▪ Matlab screen
▪ Matlab data types
▪ Matlab variables types
▪ Array, matrix, indexing
▪ Operators (arithmetic, relational, logical)
▪ Flow control
▪ Using of M-File
▪
MATLAB
▪
MATLAB is a program for doing numerical computation. It was
originally designed for solving linear algebra type problems
using matrices. It’s name is derived from
MATrix LABoratory
▪
MATLAB has since been expanded and now has built-in
functions for solving problems requiring data analysis, signal
processing, optimization, and several other types of scientific
computations. It also contains functions for 2-D and 3-D
graphics and animation.
MATLAB & Matrices
MATLAB treats all variables as matrices. For our
purposes a matrix can be thought of as an array,
in fact, that is how it is stored.
Vectors are special forms of matrices and contain
only one row OR one column.
Scalars are matrices with only one row AND one
column
MATLAB Screen
When you first open MATLAB, notice:
1.
2.
3.
4.
The command window is where you'll give MATLAB its input
and view its output.
The workspace shows you all of your current working
variables and other objects.
The history shows you all commands you used in CW.
The editor for MATLAB scripts (M-files) . To save & run the
m-file type 'F5'. To open the editor with a new or old m-file
use the command open file-name.
Matlab Screen
Command Window
◼ type commands
Current Directory
◼ View folders and m-files
Workspace
◼ View program variables
◼ Double click on a variable
to see it in the Array Editor
Command History
◼ view past commands
◼ save a whole session
using diary
Matlab data types
1. Numerical data
Scalars
◼ Vectors or Arrays
◼ Matrices
◼
2. Symbolic data
Symbolic Scalars
◼ Symbolic Arrays
◼ Symbolic Matrices
◼
7
Numerical data
Scalars
8
Numerical data
Vectors
Row Vectors
Column Vectors
9
Numerical data
Matrices
10
Symbolic data
Symbolic Scalars
11
Symbolic data
Symbolic Matrices
12
Matlab variables types
1. Built in (Predefined) variables
It is a set of constants and special values reserved in the
program, which are automatically defined in the internal
structure of the program and can be used directly without
being defined.
2. User defined variables
They are the variables that the user defines by giving numeric
or text values.
13
Special variables
ans
Default variable name for results
pi
Value of π
eps
inf
Infinity
NaN
Not a number e.g 0/0
i, j
imaginary unit i.e. square root of -1
User defined variables
Variable Names
Variable names are case sensitive (a not equal A in Matlab).
Variable names can contain up to 63 characters.
Variable names must start with a letter followed by letters, digits, and
underscores e.g x1=5 not 1x=5
Variable name cannot contain a space, and an underscore is allowed.
The variable name must not contain any special characters e.g
@,^,*,+,_,<,{,[,/….
The name of the variable must not take the name of a reserved
function in MATLAB
15
Other symbols
>>
…
,
%
;
:
prompt
continue statement on next line
separate statements and data
start comment which ends at end of line
(1)suppress output
(2)used as a row separator in a matrix
specify range
Operators (arithmetic)
+
*
/ or /
addition
subtraction
multiplication
division (note: 56/8 = 8\56)
^
‘
power
complex conjugate transpose
Matlab’s Workspace
who – current workspace variables.
whos – current workspace variables in details
(name, size, type,..).
clear all – clear workspace variables.
clc – clear the command window
clear a – clear variable a from workspace
Matlab Help
To get help on a function type “help function_name”, e.g., “help sin”.
To find a topic, type “lookfor topic”, e.g., “lookfor matrix”
For example when running “help sin”
one get
SIN Sine of argument in radians.
SIN(X) is the sine of the elements of X.
See also ASIN, SIND.
Overloaded functions
Reference page in Help browser doc sin
Array and Matrices
a vector
x=
1
2
a matrix
y=
1
2
5
1
3
2
x = [1 2 5 1]
5
1
y = [1 2 3; 5 1 4; 3 2 -1]
3
4
-1
transpose
y = x’
y=
1
2
5
1
Long Array, Matrix
t =1:10
t=
1
2
3
4 5 6
7 8
9
k =2:-0.5:-1
k=
2 1.5 1 0.5 0 -0.5 -1
B = [1:4; 5:8]
x=
1
5
2
6
3
7
4
8
10
Arrays and Matrices
x = linspace(-pi,pi,10); % creates 10
linearly-spaced elements from –pi to pi.
A = [1 2 3; 4 5 6]; % creates 2x3 matrix
A(1,2) % the element in row 1, column 2.
A(:,2) % the second column.
A(2,:) % the second row.
Some matrix functions
zeros(rows, cols) – create zero matrix
rand(rows, cols) – generate random
matrix
ones(rows, cols) – matrix with 1 in all
entries
eye (rows, cols) – identity matrix
Generating vectors from functions
zeros(M,N) MxN matrix of zeros
ones(M,N) MxN matrix of ones
rand(M,N) MxN matrix of
uniformly distributed random
numbers on (0,1)
x = zeros(1,3)
x=
0
0
0
x = ones(1,3)
x=
1
1
1
x = rand(1,3)
x=
0.9501 0.2311 0.6068
Matrix Index
The matrix indices begin from 1 (not 0 (as in C))
The matrix indices must be positive integer
Given:
A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or logicals.
A(4,2)
Error: ??? Index exceeds matrix dimensions.
Concatenation of Matrices
x = [1 2], y = [4 5], z=[ 0 0]
A = [ x y]
1
2
4
5
B = [x ; y]
12
45
C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Arrays and Matrices
A+B, A-B, 2*A, A*B
% matrix addition,
matrix subtraction, scalar multiplication,
matrix multiplication
A.*B
% element-by-element mult.
A’
% transpose of A (complexconjugate transpose)
det(A) % determinant of A
size(A) % the dimensions of a matrix
Matrices Operations
Given A and B:
Addition
Subtraction
Product
Transpose
Operators (Element by Element)
.*
./
.^
element-by-element multiplication
element-by-element division
element-by-element power
The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2
1]
A=
1
2
3
5
1
4
3
2 -1
x = A(1,:)
y = A(3 ,:)
b = x .* y
c=x./y
d = x .^2
x=
y=
b=
c=
0.33 1 -3
d=
1 2 3
3 2 -1
3 4 -3
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
1
4
9
Operators (relational\ logical )
MATLAB supports six relational operators.
Less Than
▪ Less Than or Equal
▪ Greater Than
▪ Greater Than or Equal
▪ Equal To
▪ Not Equal To
▪ And Operator
▪ Or Operator
▪
<
<=
>
>=
==
~=
&
|
Flow Control
if
for
while
break
….
Control Structures
If Statement Syntax
if (Condition_1)
Matlab Commands
elseif (Condition_2)
Matlab Commands
elseif (Condition_3)
Matlab Commands
else
Matlab Commands
end
Some Dummy Examples
if ((a>3) & (b==5))
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
elseif (b~=5)
Some Matlab Commands;
end
if (a<3)
Some Matlab Commands;
else
Some Matlab Commands;
end
If statements(Example)
if (x == 3)
disp(‘The value of x is 3.’);
elseif (x == 5)
disp(‘The value of x is 5.’);
else
disp(‘The value of x is not 3 or 5.’);
end;
Control Structures
For loop syntax
for i=Index_Array
Matlab Commands
end
Some Dummy Examples
for i=1:100
Some Matlab Commands;
end
for j=1:3:200
Some Matlab Commands;
end
for m=13:-0.2:-21
Some Matlab Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some Matlab Commands;
end
For loops(Example)
x = 0;
for i=1:2:5
x = x+i;
end
% start at 1, increment by 2
% end with 5.
This computes x = 0+1+3+5=9.
Control Structures
While Loop Syntax
while (condition)
Matlab Commands
end
Dummy Example
while ((a>3) & (b==5))
Some Matlab Commands;
end
While loops(Example)
x=7;
while (x > = 0)
x = x-2;
end;
This computes x = 7-2-2-2-2 = -1.
M-Files
An M-file might be used as a script, i.e. file consist set of
statements
In additional, one use M-files to write function, in this
case the file starts with function definition like:
function y = f(x)
function [u,v] = f(x,y,z)
File name and the name of function in the file are
usually identical, however while they are different,
MATLAB use file name to call function.
If you add additional function in same M-file, it considered
sub-function and might be called from inside the M-file
only. Only the first function might be called from outside.
Use of M-File
Click to create
a new M-File
• Extension “.m”
• A text file containing script or function or program to run
Use of M-File
Save file as Denem430.m
If you include “;” at the
end of each statement,
result will not be shown
immediately
Writing user defined functions
Functions are m-files which can be executed by
specifying some inputs and supply some desired outputs.
◼ The code telling the Matlab that an m-file is actually a
function is
◼
function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)
◼
You should write this command at the beginning of the
m-file and you should save the m-file with a file name
same as the function name
Writing user defined functions
◼
%%square.m ---- Calculates the square of a number.
◼
function y = square(x)
◼
%
calculate the square of the given number 'x'
◼
%
Arguments:
◼
% x (input)
value to be squared
◼
% y (output)
the result of the square
◼
y = x*x;
◼
end
◼
% end of square function
Interactive Example (1)
◼
Write a Matlab program to compute the following sum
∑1/i2, for i=1, 2, …, 10
two different ways:
1. 1/1+1/4+…+1/100
2. 1/100+1/81+…+1/1.
Solution
% Forward summation
forwardsum = 0;
for i=1:10
forwardsum = forwardsum+1/(i^2);
end;
% Backward summation
backwardsum = 0;
for i=10:-1:1
backwardsum = backwardsum+1/(i^2);
end;
54