Introduction to Matlab
By: Awash T.
Introduction to Matlab By:
04/17/25 Awash T. 1
What is Matlab?
MATLAB is an interactive software tool that is easy to use
and yet extremely powerful for solving science and
engineering problems
MATLAB = MATrix LABoratory
Started in the 1970s. It has now evolved into a huge system
comprising of built-in functions and toolboxes
User community size 500,000 (industry, government &
academia)
Introduction to Matlab By:
04/17/25 Awash T. 2
What is Matlab?(cont…)
Matlab is basically a high level language
which has many specialized toolboxes for
making things easier for us
How high?
Matlab
High Level
Languages such as
C, Pascal etc.
Assembly
Introduction to Matlab By:
04/17/25 Awash T. 3
Strengths of MATLAB
• Relatively easy to learn. Easy to interpret and fix
errors
• MATLAB can be used as a calculator or a
programming language
• Excellent graphics to analyze and visualize your
data
• Interfaces to external languages, such as C, C++
Introduction to Matlab By:
04/17/25 Awash T. 4
Weakness of MATLAB
• More expensive than conventional Fortran or
C compiler
• MATLAB is an interpreted language (making
it mostly slower than a compiled language
such as C, C++)
• MATLAB is designed for scientific
computation and not suitable for other things
(such as parsing text)
Introduction to Matlab By:
04/17/25 Awash T. 5
Start menu All program Matlab MATLAB
Or double click Matlab shortcut
Introduction to Matlab By:
04/17/25 Awash T. 6
Matlab Screen
Command Window
type commands
Display results
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
Introduction to Matlab By:
04/17/25 Awash T. 7
M Files (Matlab editor)
M-files are text files that contain a sequence of
MATLAB commands to achieve the required goals
Open Matlab Editor:
File New M-file (from matlab)
Or
Matlab
Desktop
Press to create
new m-file in the
matlab editor
Introduction to Matlab By:
04/17/25 Awash T. 8
Functions
Programming in Matlab.
Users can write functions which can be called from the command line.
Functions can accept input variable(s)/matrice(s) and will output
variable(s)/matrice(s).
In Matlab functions closely resemble scripts and can be written in the
Matlab editor. Matlab functions have the function keyword.
Remember that the filename of a function will be its calling function name.
Don’t overload any built-in functions by using the same filename for your
functions or scripts!
Introduction to Matlab By:
04/17/25 Awash T. 9
Functions (continued)
>> I=iterate(5) function name input
output
I=
1 4 9 16 25
function keyword
help lines for function
for statement block
Access the comments of
your Matlab functions
>> help iterate Make sure you save changes to the
m-file before you call the function!
Introduction to Matlab By:
04/17/25 Awash T. 10
Variables
Don’t have to declare type
Don’t even have to initialise
Just assign in command window
>>
>> a=12; % variable a is assigned 12
Matlab comment
prompt suppress operator
assign
command
operator
output Try the same line without the
semicolon and comments
Introduction to Matlab By:
04/17/25 Awash T. 11
Workspace
The workspace is Matlab’s memory
Can manipulate variables stored in the workspace
>> b=10;
>> c=a+b
c=
22
>>
Introduction to Matlab By:
04/17/25 Awash T. 12
Creating vectors
Coulmn separator:
Row separator: Semicolon (;)
space/coma (,)
Creating sequences:
• From : jump: till
• linespec(X1, X2, N)
generates N points between
X1 and X2.
Introduction to Matlab By:
04/17/25 Awash T. 13
Array, Matrix
a vector x = [1 2 5 1]
x =
1 2 5 1
a matrix x = [1 2 3; 5 1 4; 3 2 -1]
x =
1 2 3
5 1 4
3 2 -1
transpose y = x’ y =
1
2
5
1
Introduction to Matlab By:
04/17/25 Awash T. 14
Long Array, Matrix
t =1:10
t =
1 2 3 4 5 6 7 8 9 10
k =2:-0.5:-1
k =
2 1.5 1 0.5 0 -0.5 -1
B = [1:4; 5:8]
B =
1 2 3 4
5 6 7 8
Introduction to Matlab By:
04/17/25 Awash T. 15
Generating Vectors from
functions
zeros(M,N) MxN matrix of zeros x = zeros(1,3)
x =
0 0 0
ones(M,N) MxN matrix of ones
x = ones(1,3)
x =
1 1 1
rand(M,N) MxN matrix of uniformly
distributed x = rand(1,3)
random
x =
numbers on (0,1)
0.9501 0.2311 0.6068
Introduction to Matlab By:
04/17/25 Awash T. 16
Matrices
Don’t need to initialise type, or dimensions
>>A = [3 2 1; 5 1 0; 2 1 7]
A=
3 2 1 square brackets to define matrices
5 1 0
semicolon for next row in matrix
2 1 7
>>
Introduction to Matlab By:
04/17/25 Awash T. 17
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.
Introduction to Matlab By:
04/17/25 Awash T. 18
Concatenation of Matrices
x = [1 2], y = [4 5], z=[ 0 0]
A = [ x y]
1 2 4 5
B = [x ; y]
1 2
4 5
C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.
Introduction to Matlab By:
04/17/25 Awash T. 19
Manipulating Matrices
A=
Access elements of a matrix 2 1 3
1 0 5
>>A(1,2) 1 7 2
ans=
indices of matrix element(s)
2
Remember Matrix(row,column)
Naming convention Matrix variables start with
a capital letter while vectors or scalar
variables start with a simple letter
Introduction to Matlab By:
04/17/25 Awash T. 20
The : operator and matrices
A=
>>A(3,2:3) 3 2 1
ans = 5 1 0
2 1 7
1 7
>>A(:,2)
ans =
2
1
What’ll happen if you type A(:,:) ?
1
Introduction to Matlab By:
04/17/25 Awash T. 21
Manipulating Matrices A=
3 2 1
5 1 0
2 1 7
B=
>> A ' % transpose 1 3 1
4 9 5
>> B*A % matrix multiplication 2 7 2
>> B.*A% element by element multiplication
>> B/A % matrix division
Enter matrix B
>> B./A % element by element division into the Matlab
workspace
>> [B A] % Join matrices (horizontally)
>> [B; A] % Join matrices (vertically)
Create matrices A and B and try out the the matrix operators in this slide
Introduction to Matlab By:
04/17/25 Awash T. 22
The use of “.” – “Element”
Element
Operation
A= [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1
b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Introduction to Matlab By:
04/17/25 Awash T. 23
MATLAB Special Variables
ans Default variable name for results
pi Value of
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realminThe smallest usable positive real number
realmax The largest usable positive real number
Introduction to Matlab By:
04/17/25 Awash T. 24
A few important commands
clc: clears command window
clf: clears current figure
clear: clear variables in the WS
Ctrl+c: aborts the execution of the program
exit: exits Matlab
!(command): runs the command in the
operating system (ex. dir, copy …)
save/load (WS): saves and loads the WS
Introduction to Matlab By:
04/17/25 Awash T. 25
Other built-in functions
sqrt(x) = square root of x
abs(x) = absolute value or modulus of x
sign(x) = sign of x; returns +1 or -1
round(x) = rounds x to the nearest integer
exp(x) = exponential of x
log(x) = natural logarithm of x
log10(x) = logarithm of x in base 10
Introduction to Matlab By:
04/17/25 Awash T. 26
Flow Control Constructs
Logic Control:
IF / ELSEIF / ELSE
SWITCH / CASE / OTHERWISE
Iterative Loops:
FOR
WHILE
Introduction to Matlab By:
04/17/25 Awash T. 27
The if, elseif and else
•statements
Works on Conditional statements
• Short-circuited in MATLAB - once a
condition is true, the sequence
if
if II ==
== JJ
terminates.
A(I,J)
A(I,J) == 2;
2;
elseif
elseif abs(I-J)
abs(I-J) ==
== 11
A(I,J)
A(I,J) == -1;
-1;
if (Condition_1) else
else
Matlab Commands A(I,J)
A(I,J) == 0;
0;
end
end
elseif (Condition_2)
Matlab Commands
elseif (Condition_3) »if_examp
Matlab Commands
else
Matlab Commands
Introduction to Matlab By:
end
04/17/25 Awash T. 28
Switch, Case, and Otherwise
switch
switch input_num
input_num
More efficient than elseif statements case
case -1
-1
input_str
input_str == 'minus
'minus one';
Only the first matching case is one';
case
case 00
executed input_str
input_str == 'zero';
'zero';
case
case 11
input_str
input_str == 'plus
'plus one';
one';
case
case {-10,10}
{-10,10}
input_str
input_str == '+/-
'+/- ten';
ten';
otherwise
otherwise
input_str
input_str == 'other
'other value';
value';
end
end
»switch_examp
Introduction to Matlab By:
04/17/25 Awash T. 29
The for loop
N=10;
N=10;
• Similar to other programming
for
for II == 1:N
1:N
languages for
for JJ == 1:N
1:N
A(I,J)
A(I,J) == 1/(I+J-1);
1/(I+J-1);
• Repeats loop a set number of times
end
end
(based on index) end
end
For loop syntax
for i=Index_Array
»for_examp
Matlab Commands
end
Introduction to Matlab By:
04/17/25 Awash T. 30
The while loop
• Similar to other programming
languages
I=1;
I=1; N=10;
N=10;
• Repeats loop until logical while
while I<=N
I<=N
condition returns FALSE. J=1;
J=1;
while
while J<=N
J<=N
• Can be nested. A(I,J)=1/(I+J-1);
A(I,J)=1/(I+J-1);
J=J+1;
J=J+1;
For while loop syntax end
end
I=I+1;
I=I+1;
while (condition)
end
end
Matlab Commands
end
»while_examp
Introduction to Matlab By:
04/17/25 Awash T. 31
Recall: Array Operations
Using Array Operations:
Density
Density == Mass(I,J)/(Length.*Width.*Height);
Mass(I,J)/(Length.*Width.*Height);
Using Loops:
[rows,
[rows, cols]
cols] == size(M);
size(M);
for
for II == 1:rows
1:rows
for
for JJ == 1:cols
1:cols
Density(I,J)
Density(I,J) == M(I,J)/(L(I,J)*W(I,J)*H(I,J));
M(I,J)/(L(I,J)*W(I,J)*H(I,J));
end
end
end
end
»array_vs_loops
Introduction to Matlab By:
04/17/25 Awash T. 32
Plotting with MATLAB
MATLAB will plot one vector vs. another. The first one
will be treated as the abscissa (or x) vector and the
second as the ordinate (or y) vector. The vectors have
to be the same length.
MATLAB will also plot a vector vs. its own index. The
index will be treated as the abscissa vector. Given a
vector “time” and a vector “dist” we could say:
>> plot (time, dist) % plotting versus time
>> plot (dist) % plotting versus index
Introduction to Matlab By:
04/17/25 Awash T. 33
Plotting with MATLAB
There are commands in MATLAB to "annotate" a plot to
put on axis labels, titles, and legends. For example:
>> % To put a label on the axes we would use:
>> xlabel ('X-axis label')
>> ylabel ('Y-axis label')
>> % To put a title on the plot, we would use:
>> title ('Title of my plot')
Introduction to Matlab By:
04/17/25 Awash T. 34
Plotting with MATLAB
Vectors may be extracted from matrices. Normally, we
wish to plot one column vs. another. If we have a matrix
“mydata” with two columns, we can obtain the columns
as a vectors with the assignments as follows:
>> first_vector = mydata ( : , 1) ; % First column
>> second_vector = mydata ( : , 2) ; % Second one
>>% and we can plot the data
>> plot ( first_vector , second_vector )
Introduction to Matlab By:
04/17/25 Awash T. 35
Visualisation - plotting data
>> figure % create new figure
>> t=0:pi/12:8*pi;
>> y=cos(t); Plot style
>> plot(t,y,‘b.-')
Investigate the function
>> y=A*cos(w*t+phi);
for different values of phi (eg: 0, pi/4, pi/3,
pi/2), w (eg: 1, 2, 3, 4) and A (eg: 1, 0.5, 2). Use
the hold on Matlab command to display your
plots in the same figure. Remember to type A = amplitude
hold off to go back to normal plotting mode. phi = phase
Try using different plot styles (help plot) w = angular frequency = 2*pi*frequency
Introduction to Matlab By:
04/17/25 Awash T. 36
Plots
MATLAB is very good at visualizing mathematical
functions. Use “plot” command for the basic plot
1
0.8
>> x=-8:0.1:8; 0.6
>> y=sin(x); 0.4
>> plot(x,y) 0.2
>> xlabel('X')
sin(X)
0
>> ylabel('sin(X)') -0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
X
Introduction to Matlab By:
04/17/25 Awash T. 37
Plots
Plotting multiple figures on the same axis
1
sin(X)
0.8 cos(X)
0.6
>> x=-8:0.1:8;
0.4
>> y=sin(x);
>> z = cos(x); 0.2
>> plot(x,y,'+-',x,z,'o-') 0
>> legend('sin(X)','cos(X)') -0.2
-0.4
-0.6
-0.8
-1
-8 -6 -4 -2 0 2 4 6 8
Introduction to Matlab By:
04/17/25 Awash T. 38
Plots
To plot 3 dimensional graph using MAT LAB
Introduction to Matlab By:
04/17/25 Awash T. 39
Basic Task: Plot the function
sin(x) between 0≤x≤4π
Create an x-array of 100 samples between 0
and 4π.
>>x=linspace(0,4*pi,100);
Calculate sin(.) of the x-array
1
0.8
0.6
>>y=sin(x); 0.4
0.2
Plot the y-array -0.2
-0.4
-0.6
>>plot(y) -0.8
-1
0 10 20 30 40 50 60 70 80 90 100
Introduction to Matlab By:
04/17/25 Awash T. 40
Plot the function e-x/3sin(x)
between 0≤x≤4π
Create an x-array of 100 samples between 0
and 4π.
>>x=linspace(0,4*pi,100);
Calculate sin(.) of the x-array
>>y=sin(x);
Calculate e-x/3 of the x-array
>>y1=exp(-x/3);
Multiply the arrays y and y1
>>y2=y*y1;
Introduction to Matlab By:
04/17/25 Awash T. 41
Plot the function e-x/3sin(x)
between 0≤x≤4π
Multiply the arrays y and y1 correctly
>>y2=y.*y1;
Plot the y2-array
0.7
>>plot(y2) 0.6
0.5
0.4
0.3
0.2
0.1
-0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
Introduction to Matlab By:
04/17/25 Awash T. 42
Display Facilities 0.7
0.6
0.5
plot(.) 0.4
0.3
0.2
Example: 0.1
>>x=linspace(0,4*pi,100); 0
>>y=sin(x); -0.1
>>plot(y) -0.2
>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100
0.7
stem(.) 0.6
0.5
0.4
0.3
0.2
Example: 0.1
>>stem(y) 0
>>stem(x,y) -0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
Introduction to Matlab By:
04/17/25 Awash T. 43
Display Facilities
title(.)
This is the sinus function
>>title(‘This is the sinus function’) 1
0.8
xlabel(.) 0.6
0.4
>>xlabel(‘x (secs)’) 0.2
sin(x)
0
ylabel(.) -0.2
-0.4
-0.6
-0.8
>>ylabel(‘sin(x)’) -1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
Introduction to Matlab By:
04/17/25 Awash T. 44
The ‘inline’ command
The inline command can be used for simple,
one-line functions. For example, to create
f(x) = x^3 – 5*x^2 -x +2 :
>> f = inline(‘x^3 -5*x^2 - x+2’)
Introduction to Matlab By:
04/17/25 Awash T. 45
2.1 Clearing Variables
You can use the command “clear all” to delete all the
variables present in the workspace
You can also clear specific variables using:
>> clear Variable_Name
Introduction to Matlab By:
04/17/25 Awash T. 46