MATLAB
for Technical Computing
Naveed ur Rehman
http://www.naveedurrehman.com/
Outline
1. Introduction to MATLAB and programming
2. Workspace, variables and arrays
3. Using operators, expressions and
statements
4. Repeating and decision-making
5. Different methods for input and output
6. Common functions
7. Logical vectors
naveedurrehman.com
Outline
8. Matrices and string arrays
9. Introduction to graphics
10. Loops
11. Custom functions and M-files
naveedurrehman.com
Introduction
• MATLAB stands for Matrix Laboratory
• The system was designed to make matrix
computations particularly easy
• It is a powerful computing system for
handling scientific and engineering
calculations.
• MATLAB system is Interpreter.
naveedurrehman.com
Introduction
An Array
naveedurrehman.com
Here, A is of order (m, n) = (2, 3)
Element: A (1,2)
Introduction
Why MATLAB?
naveedurrehman.com
• MATLAB can be used interactively
• Easy format: Many science and
engineering problems can be solved by
entering one or two commands
• Rich with 2D and 3D plotting capabilities
• Countless libraries and still developing
Introduction
What you should already know?
naveedurrehman.com
• The mathematics associated with the
problem you want to solve in MATLAB.
• The logical plan or algorithm for solving a
particular problem.
Introduction
What to learn in MATLAB?
naveedurrehman.com
• The exact rules for writing MATLAB
statements and using MATLAB utilities
• Converting algorithm into MATLAB
statements and/or program
Introduction
What you will learn with experience?
naveedurrehman.com
• To design, develop and implement
computational and graphical tools to do
relatively complex problems
• To develop a toolbox of your own that
helps you solve problems of interest
• To adjust the look of MATLAB to make
interaction more user-friendly
Introduction
User-interface: MATLAB Desktop
naveedurrehman.com
Introduction
Using command prompt:
naveedurrehman.com
• Command line: The line with >> prompt
• Command-line editing:
• Use Backspace, Left-arrow, Right-arrow
• Up-arrow and Down-arrow for accessing history
• Smart recall: type some character and press Up-
arrow and Down-arrow
• Execution: Enter
Introduction
Training methodology
naveedurrehman.com
1. Presentation + Code execution by Trainer
in Classroom or Lab
2. Code execution + practice problems by
Attendees in Lab
Arithmetic
naveedurrehman.com
Addition: 3+2
Subtraction: 3-2
Multiplication: 3*2
Division: 3/2 or 23
Exponent: 3^2
Arithmetic
1/0
naveedurrehman.com
Infinity:
inf + 3
Not-a-Number (NaN):
0/0
Variables
naveedurrehman.com
Save value in a variable:
x = 3
x = 3;
x
Variables are case-sensitive:
T = 2
t = 3
Z = t+T;
Variable naming rules
naveedurrehman.com
1. It may consist only of the letters A-Z,a-z,
the digits 0-9, and the underscore ( _ ).
2. It must start with a letter.
Using functions
a = sqrt(4)
naveedurrehman.com
a = 4
Using functions
naveedurrehman.com
• pi -> it’s a pre-defined constant
• abs(x) sqrt(x)
• sin(x) cos(x) tan(x)
asin(x) acos(x) atan(x)
sinh(x) cosh(x) tanh(x)
asinh(x) acosh(x) atanh(x)
• atan2(y,x) hypot(y,x)
• ceil(x), floor(x)
• log(x) log10(x) exp(x)
Using functions
naveedurrehman.com
fix and rem
Converting 40 inches to feet-inch.
feet = fix(40/12)
inches = rem(40, 12)
Using commands
naveedurrehman.com
• help function or command
• clc
• whos
• clear
• clear variable
• date
• calendar
help sin
Vectors
naveedurrehman.com
X=[3,2]
X=[3;2]
Row vectors:
Column vector:
X= [1:10]
X= [0:2:10]
Vectors
naveedurrehman.com
X=1:10
Y = 2 .* X
Operations with scalar values:
Addition: 3.+X
Subtraction: 3.-X
Multiplication: 3.*X
Division: 3./X or X.3
Exponent: X.^3
Vectors
naveedurrehman.com
X=0:180
Y = sin(X.*pi/180)
Operations with functions:
Vectors
naveedurrehman.com
X=10:15
Y=30:35
Z=X .* Y
Scalar operations with vectors:
Each element of X is multiplied by the
respective element of Y.
Matrices
naveedurrehman.com
X = [1 2; 3 4]
A 2D matrix:
X =
1 2
3 4
Matrices
naveedurrehman.com
X = [1 2; 3 4]
Y = 2 .* X
Scalar operations with matrix:
X = [1 2; 3 4]
Y = [5 6; 7 8]
Z = X.*Y
Scalar operations between matrices:
Matrices
naveedurrehman.com
X = [1 2; 3 4]
Y = [5 6; 7 8]
Z = X*Y
Vector operations between matrices:
Matrices
naveedurrehman.com
Y = [1 4 8; 0 -1 4]'
Transpose:
Matrices
naveedurrehman.com
M = magic(3)
Magic square matrix:
the rows, columns, and main diagonal add
up to the same value in a magic matrix.
Matrices
naveedurrehman.com
R = rand(2,3)
Random matrix:
Arithmetic with Matrices
naveedurrehman.com
k = min(A)
Minimum:
k = max(A)
Maximum:
k = mean(A)
Mean:
k = length(A)
Length:
Arithmetic with Matrices
naveedurrehman.com
k = sum(A)
Sum:
k = sum(A .* B)
Sum of products:
k = prod(A)
Product:
Accessing elements
naveedurrehman.com
R = rand(5,7);
a = R(1,2)
b = R(1:5,2)
c = R(1:4,1:3)
Linear equations
naveedurrehman.com
A = [1 2; 2 -1]
B = [4; 3]
R = AB
Solution with matrix method:
Linear equations
naveedurrehman.com
[x,y]=solve('x+2*y=4','2*x-y=3')
Solution with built-in solve function:
Polynomials
naveedurrehman.com
P = [1 7 0 -5 9]
A polynomial can be represented as a vector.
Example:
To solve a polynomial at some value of x:
polyval(P,4)
Polynomials
naveedurrehman.com
P = [1 7 0 -5 9];
R = roots(P)
Roots of a polynomial:
R = [3 4 5 2];
P = poly(R)
Generating polynomial from roots:
Polynomials
naveedurrehman.com
X = [1 2 3 4 5 6];
Y = [5.5 43.1 128 290.7 498.4 978.67];
P = polyfit(X,Y,4)
Fitting a polynomial using least-square
method:
Plotting
naveedurrehman.com
X=0:360
Y=sin(X.*pi/180)
plot(X,Y)
Plot function:
0 50 100 150 200 250 300 350 400
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Plotting
naveedurrehman.com
Options
Plotting
naveedurrehman.com
X=0:10:360
Y=sin(X.*pi/180)
plot(X,Y,'r+')
X=0:10:360
Y=sin(X.*pi/180)
plot(X,Y,'r+-')
Plotting
naveedurrehman.com
title('some graph title')
xlabel('some label on x-axis')
ylabel('some label on y-axis')
grid %use grid or grid off
axis equal
Plotting
naveedurrehman.com
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y,'r', x, g,'b')
legend(Sin(x)', 'Cos(x)')
Multiple functions on same graphs:
Plotting
naveedurrehman.com
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y,'r')
figure
plot(x, g,'b')
Multiple functions on multiple graphs:
Plotting
naveedurrehman.com
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
subplot(1,2,1)
plot(x, y,'r')
subplot(1,2,2)
plot(x, g,'b')
Multiple functions as subgraphs:
Graphics
naveedurrehman.com
x = [1:10];
y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
bar(x,y)
xlabel('Student')
ylabel('Score')
title('First Sem:')
Bar graphs:
Graphics
naveedurrehman.com
[x,y] = meshgrid(-5:0.1:5,-3:0.1:3);
g = x.^2 + y;
contour(x,y,g,20)
xlabel('x')
ylabel('y')
Contour graphs:
Graphics
naveedurrehman.com
[x,y] = meshgrid(-2:.2:2, -2:.2:2);
z = x .* exp(-x.^2 - y.^2);
surf(x,y,z)
xlabel('x')
ylabel('y')
zlabel('z')
Surface graphs:
Equation plotting
naveedurrehman.com
ezplot('2*x+y^2=10')
ezplot function:
-6 -4 -2 0 2 4 6
-6
-4
-2
0
2
4
6
x
y
2 x+y2
=10
Symbolic operations
naveedurrehman.com
a = sym('a');
b = sym('b');
c = 2*a
d = 2*c+b*c
Symbolic diff. and int.
naveedurrehman.com
Differentiation:
syms t
f = 3*t^2 + 2*t^(-2);
diff(f)
Integration and area under the curve:
syms x
f = 2*x^5
int(f)
area = double(int(f, 1.8, 2.3))
Symbolic expand and collect
naveedurrehman.com
Expand:
syms x
syms y
expand((x-5)*(x+9))
expand(sin(2*x))
expand(cos(x+y))
Symbolic factor. and simplification
naveedurrehman.com
Factorization:
syms x
syms y
factor(x^3 - y^3)
Simplification:
syms x
syms y
simplify((x^4-16)/(x^2-4))
Complex numbers
naveedurrehman.com
Z = 2 + 3*i
Defining:
Functions:
R = real(Z)
G = imag(Z)
C = conj(Z)
Complex numbers
naveedurrehman.com
S = sqrt(Z) % using De Moivre's formula
More functions:
E = exp(Z)
A = angle(Z) % in radians
In polar coordinates:
M = abs(Z) % magnitude
M-Files: Programming mode
naveedurrehman.com
M-Files are also called Matlab program files.
• Go to File > New > M-File or just type edit
to start with a new m-file.
• Always save M-File file before execution.
Ctrl+S can be used as keyboard shortcut.
• To execute codes, use F5. If the Current
Directory is set, you may drag-drop the
file or type its file name (with out
extension).
Displaying in M-Files
naveedurrehman.com
Use disp function.
R = rand(5,1)
disp(R)
disp(R’)
disp([R, R])
disp(['Good number is ', num2str(1+7)])
Resetting in M-Files
naveedurrehman.com
Use clear and clc in the beginning of any
program. This will:
1. Delete all variables from workspace
2. Wipe the command window and set
cursor at top.
Comments in M-Files
naveedurrehman.com
1. Use % symbol before program comments.
2. The Comment and Uncomment submenu
in Text menu in editor’s tab can also be
used.
3. Program comments are not read by
MATLAB interpreter.
Sample program: Speed
naveedurrehman.com
s = 20;
t = 300;
v = s/t;
disp( 'Speed required is:' );
disp( v );
Sample program: SpeedS
naveedurrehman.com
s = 10:10:1000;
t = 300;
v = s./t;
disp([s' v']);
Sample program: Balance
naveedurrehman.com
balance = 1000;
rate = 0.09;
interest = rate * balance;
balance = balance + interest;
disp( 'New balance:' );
disp( balance );
Sample program: Vertical Motion
naveedurrehman.com
g = 9.81; % acceleration due to gravity
u = 60; % initial velocity in metres/sec
t = 0 : 0.1 : 12.3; % time in seconds
s = u .* t + g / 2 .* t .^ 2; % vertical displacement in metres
plot(t, s)
title( 'Vertical motion under gravity' )
xlabel( 'time' )
ylabel( 'vertical displacement' )
grid
disp( [t' s'] ) % display a table
Taking input from user
naveedurrehman.com
Use input function to take input from user.
A = input('How many apples: ');
Numeric input:
N = input('Enter your name: ','s');
String input:
Tic-toc
naveedurrehman.com
Tic-toc can be used for knowing execution
time.
tic
A = input('How many apples: ');
toc
Saving and loading via files
naveedurrehman.com
save and load commands are used to save
and load a variable via files:
A = rand(3,3);
save record.txt A -ascii
C = load('record.txt')
Files can be generated by external programs
or data loggers can be read using load.
Communication with MS Excel
naveedurrehman.com
csvread and csvwrite commands are used to
read and save variable in MS Excel format file:
A = rand(3,3);
csvwrite('record.csv',A)
B = csvread('record.csv')
Predicate expression
naveedurrehman.com
1. A predicate is one in which relational
and/or logical operator(s) are used.
2. They result in either true (1) or false (0).
Relational operators
naveedurrehman.com
5 > 3
A = 5;
B = 10;
C = B >= A
== Equals to
< Less than
> Greater than
<= Less than or equals to
>= Greater than or equals to
~= Not equals to
Logical operators
naveedurrehman.com
(5 > 3) & (10 < 4)
A = 5;
B = 10;
C = 30;
D = 100;
E = (B >= A) | (D<C)
~ Logical Not
| Logical OR
& Logical AND
AND
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
OR
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
Condition using if constructs
naveedurrehman.com
if predicate
statements
end
if predicate
statements
else
statements
end
if predicate
statements
elseif predicate
statements
elseif predicate
statements
end
if predicate
statements
elseif predicate
statements
else
statements
end
1
2
3 4
Example: If-end
naveedurrehman.com
r = rand
if r > 0.5
disp( 'greater indeed' )
end
1
Example: If-else-end
naveedurrehman.com
r = rand
if r > 0.5
disp( 'greater indeed' )
else
disp( ‘smaller indeed' )
end
2
Example: If-elseif-end
naveedurrehman.com
r = rand
if r == 0.5
disp( 'equals indeed' )
elseif (r > 0.5)
disp( 'greater indeed' )
end
3
Example: If-elseif-else-end
naveedurrehman.com
r = rand
if r == 0.5
disp( 'equals indeed' )
elseif (r > 0.5)
disp( 'greater indeed' )
else
disp( ‘smaller indeed' )
end
4
Repetition using For loop
naveedurrehman.com
for variable = expr
statements...
end
expr can be like: f:l or f:i:l
1. 1:10
2. 0:2:10
3. 10:-1:0
For loop: Factorial program
naveedurrehman.com
n = 10;
fact = 1;
for k = 1:n
fact = k * fact;
disp( [k fact] )
end
Repetition using While loop
naveedurrehman.com
while expr
statements
end
expr is a predicate expression.
While loop: Numbering program
naveedurrehman.com
k = 1
while k < 10
disp(k);
k = k + 1;
end
Controlling in loops
naveedurrehman.com
1. To terminate a loop at any iteration:
break
2. To pass control to the next iteration:
continue
Logical vectors
naveedurrehman.com
The elements of a logical vector are either 1
or 0. In the following example, G and H are
logical vectors:
R = rand(1,10);
G = R>0.5;
H = (R>=0.5) | (R<=0.3);
Logical vectors
naveedurrehman.com
Counting true and false:
R = rand(1,100);
T = sum(R>0.5);
F = length(R) - sum(R>0.5);
Logical vectors
naveedurrehman.com
Functions:
Ra = [0 0 0 0 1];
Rb = [0 0 0 0 0];
any(Ra)
any(Rb)
any: is any true element exist?
Logical vectors
naveedurrehman.com
Functions:
Ra = [0 0 1 0 1];
Rb = [1 1 1 1 1];
all(Ra)
all(Rb)
all: are all elements true?
Logical vectors
naveedurrehman.com
Functions:
exist('a') %where a is a variable name
exist: is a variable exists in workspace?
R = [0 0 1 0 1];
find(R)
find: returns subscripts on true elements.
Logical vectors
naveedurrehman.com
Example: calculate sixes in a dice game.
a = 1;
b = 6;
t = 500;
r = floor(a + (b-a+1).*rand(1,t)); % [a, b]
sixes = sum(r==6)
Sorting
naveedurrehman.com
A vector or matrix can be sort in ascending or
descending order.
v = rand(1,10);
a = sort(v);
d = sort(v,'descend');
Primes and factors
naveedurrehman.com
primes:
v = primes(100)
isprime:
v = isprime(97)
factors:
v = factor(96)
Evaluation of expression
naveedurrehman.com
Lets say:
eqn = '(1/2)*x+x^2-3'
Evaluation:
x = 4;
y = eval(eqn)
Vectorization of expression
naveedurrehman.com
Lets say:
eqn = '(1/2)*x+x^2-3'
Vectroization:
v = vectorize(eqn);
Evaluation of vectorized expression
naveedurrehman.com
yeqn = '(1/2)*x+x^2-3';
x = 0:20;
y = eval(vectorize(yeqn));
disp([x' y'])
plot(x,y)
Ordinary differential equations
naveedurrehman.com
dsolve('Dy = x*y','x')
First order ODE:
Solution:
r = dsolve('Dy = x*y','y(1)=1','x')
Numerical solution for initial condition:
Ordinary differential equations
naveedurrehman.com
r = dsolve('Dy = x*y','y(1)=1','x');
x = 0:0.1:5;
y = eval(vectorize(r))
plot(x,y)
Solution set and plot when independent
variable x ranges from 0 to 20.
@
Ordinary differential equations
naveedurrehman.com
eqn = 'D2y + 8*Dy + 2*y = cos(x)';
inits = 'y(0)=0, Dy(0)=1';
r = dsolve(eqn,inits,'x');
x = 0:0.1:20;
y = eval(vectorize(r));
disp([x' y']);
plot(x,y);
Second order ODE:
Ordinary differential equations
naveedurrehman.com
[x,y,z]=dsolve('Dx=x+2*y-
z','Dy=x+z','Dz=4*x-4*y+5*z')
System of ODEs:
Ordinary differential equations
naveedurrehman.com
inits='x(0)=1,y(0)=2,z(0)=3';
[x,y,z]=dsolve('Dx=x+2*y-
z','Dy=x+z','Dz=4*x-4*y+5*z',inits)
System of ODEs with Numerical solution for
initial conditions:
Ordinary differential equations
naveedurrehman.com
inits='x(0)=1,y(0)=2,z(0)=3';
[x,y,z]=dsolve('Dx=x+2*y-
z','Dy=x+z','Dz=4*x-4*y+5*z',inits);
t=0:0.02:.5;
xx=eval(vectorize(x));
yy=eval(vectorize(y));
zz=eval(vectorize(z));
plot(t, xx, 'r',t, yy, 'g',t, zz,'b');
System of ODEs with solution set and plot:
Example: Palindrome!
naveedurrehman.com
Ask user to input a number. Check if it is
palindrome or not.
Hint:
A palindrome number is a number such that if
we reverse it, it will not change. Use:
1. num2str: converts number to a string
2. fliplr: flips a string, left to right
3. str2num: converts string to a number
Example: Projectile motion
naveedurrehman.com
Ask user to enter initial velocity and angle from
horizontal for a projectile motion.
Calculate:
1. Range
2. Flight time
3. Max. height
Also plot:
1. Projectile trajectory (x vs. y)
2. Projectile angle vs. speed
Example: Projectile motion
naveedurrehman.com
Range:
Flight time:
Max. height:
Trajectory:
Instant. Velocity & angle:
Example: Projectile motion
naveedurrehman.com
Example: Projectile motion
naveedurrehman.com
Example: pi using Monte Carlo
naveedurrehman.com
R
Area of circle / Area of square = pi*r^2 / (2r)^2
C / S = pi / 4
pi = 4 * C / S
Prove that the
value of pi is 3.142
Example: pi using Monte Carlo
naveedurrehman.com
Procedure:
1. Throw T number of darts
2. Count the number of darts falling inside Circle (C)
3. Count the number of darts falling inside Square (S)
4. Calculate pi = 4 * C / S
Example: pi using Monte Carlo
naveedurrehman.com
Hint:
1. Assume that radius (R) is 1 unit.
2. Generate T number of X and Y random numbers
between 0 and 1. Let the dart fall on square at
(X,Y).
3. Calculate position of dart by P2 = X2 + Y2
4. Increment in C if P <= 1
5. Darts inside square will be S = T
Example: Lookup
naveedurrehman.com
Investment Profit
10 100
20 250
30 400
40 390
50 380
Find out the maximum profit and optimum
investment.
Anonymous (in-line) functions
naveedurrehman.com
function_name = @(arglist)expression
Usage:
power = @(x, n) x.^n;
result1 = power(7, 3)
result2 = power(49, 0.5)
result3 = power(10, -10)
result4 = power (4.5, 1.5)
Anonymous (in-line) functions
naveedurrehman.com
Write an anonymous function to calculate
average of three numbers.
myavg = @(a, b, c) (a+b+c)/3;
....
...
...
result = myavg (1,2, 3)
M-File functions
naveedurrehman.com
function [out1,out2, ..., outN] =
myfun(in1,in2,in3, ..., inN)
Note:
1. Functions should be saved in separate
files.
2. Name of file should be as same as the
name of function.
M-File functions
naveedurrehman.com
function [sum,avg] = mysumavg(n1, n2, n3)
%This function calculates the sum and
% average of the three given numbers
sum = n1+n2+n3;
avg = sum/3;
mysumavg.m:
[thesum,theavg] = mysumavg(1,2,3)
program.m:
M-File functions
naveedurrehman.com
Write a function to calculate roots of a
quadratic equation.
M-File functions with subfunctions
naveedurrehman.com
function [o1,o2…] = function(in1,in2…)
….
end
function [o1,o2…] = subfunction(in1,in2…)
….
end
function.m:
M-File functions with subfunctions
naveedurrehman.com
Note:
1. File name should be as same as main
function’s name
2. Variables of main function are unknown
in subfunction
3. Variables of sub function are unknown in
main function
M-File functions with subfunctions
naveedurrehman.com
Write a function to calculate roots of a
quadratic equation. The discriminant should
be calculated in a sub function.
M-File functions with nested funcs
naveedurrehman.com
function [o1,o2…] = function(in1,in2…)
….
function [o1,o2…] = nestfunction(in1,in2…)
….
End
…
end
function.m:
M-File functions with nested funcs
naveedurrehman.com
Note:
1. File name should be as same as main
function’s name
2. Variables of main function and sub
functions are known.
M-File functions with nested funcs
naveedurrehman.com
Write a function calculate roots of a
quadratic equation. The discriminant should
be calculated in a nested function.
Global variables
naveedurrehman.com
These variables are known in all program as
well as In functions.
Global variables
naveedurrehman.com
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end
THANK YOU!
Naveed ur Rehman
http://www.naveedurrehman.com/

MATLAB for Technical Computing