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
8. Matrices and string arrays
9. Introduction to graphics
10. Loops
11. Custom functions and M-files
2. 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
3. Outline
8. Matrices and string arrays
9. Introduction to graphics
10. Loops
11. Custom functions and M-files
naveedurrehman.com
4. 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
6. 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
7. 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.
8. 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
9. 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
12. 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
27. 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:
37. 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)
52. 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))
53. Symbolic expand and collect
naveedurrehman.com
Expand:
syms x
syms y
expand((x-5)*(x+9))
expand(sin(2*x))
expand(cos(x+y))
54. 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))
56. 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
57. 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).
59. 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.
60. 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.
64. 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
65. 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:
67. 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.
68. 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')
70. 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
71. 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
72. 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
82. 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);
99. 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
100. 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
104. 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
105. 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
106. 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
111. 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:
113. M-File functions with subfunctions
naveedurrehman.com
function [o1,o2…] = function(in1,in2…)
….
end
function [o1,o2…] = subfunction(in1,in2…)
….
end
function.m:
114. 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
115. 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.
116. M-File functions with nested funcs
naveedurrehman.com
function [o1,o2…] = function(in1,in2…)
….
function [o1,o2…] = nestfunction(in1,in2…)
….
End
…
end
function.m:
117. 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.
118. 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.