Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
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
s...
Outline
8. Matrices and string arrays
9. Introduction to graphics
10. Loops
11. Custom functions and M-files
naveedurrehma...
Introduction
• MATLAB stands for Matrix Laboratory
• The system was designed to make matrix
computations particularly easy...
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...
Introduction
What you should already know?
naveedurrehman.com
• The mathematics associated with the
problem you want to so...
Introduction
What to learn in MATLAB?
naveedurrehman.com
• The exact rules for writing MATLAB
statements and using MATLAB ...
Introduction
What you will learn with experience?
naveedurrehman.com
• To design, develop and implement
computational and ...
Introduction
User-interface: MATLAB Desktop
naveedurrehman.com
Introduction
Using command prompt:
naveedurrehman.com
• Command line: The line with >> prompt
• Command-line editing:
• Us...
Introduction
Training methodology
naveedurrehman.com
1. Presentation + Code execution by Trainer
in Classroom or Lab
2. Co...
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...
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) aco...
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 ...
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
Multiplicatio...
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...
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.*...
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 valu...
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 polynomia...
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...
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 poly...
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....
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 %...
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)')...
Plotting
naveedurrehman.com
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y,'r')
figure
plot(x, g,'b')
Multiple func...
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(...
Graphics
naveedurrehman.com
x = [1:10];
y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
bar(x,y)
xlabel('Student')
ylabel('S...
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')
C...
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...
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 unde...
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...
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 ra...
M-Files: Programming mode
naveedurrehman.com
M-Files are also called Matlab program files.
• Go to File > New > M-File or ...
Displaying in M-Files
naveedurrehman.com
Use disp function.
R = rand(5,1)
disp(R)
disp(R’)
disp([R, R])
disp(['Good number...
Resetting in M-Files
naveedurrehman.com
Use clear and clc in the beginning of any
program. This will:
1. Delete all variab...
Comments in M-Files
naveedurrehman.com
1. Use % symbol before program comments.
2. The Comment and Uncomment submenu
in Te...
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 + int...
Sample program: Vertical Motion
naveedurrehman.com
g = 9.81; % acceleration due to gravity
u = 60; % initial velocity in m...
Taking input from user
naveedurrehman.com
Use input function to take input from user.
A = input('How many apples: ');
Nume...
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 =...
Communication with MS Excel
naveedurrehman.com
csvread and csvwrite commands are used to
read and save variable in MS Exce...
Predicate expression
naveedurrehman.com
1. A predicate is one in which relational
and/or logical operator(s) are used.
2. ...
Relational operators
naveedurrehman.com
5 > 3
A = 5;
B = 10;
C = B >= A
== Equals to
< Less than
> Greater than
<= Less th...
Logical operators
naveedurrehman.com
(5 > 3) & (10 < 4)
A = 5;
B = 10;
C = 30;
D = 100;
E = (B >= A) | (D<C)
~ Logical Not...
Condition using if constructs
naveedurrehman.com
if predicate
statements
end
if predicate
statements
else
statements
end
i...
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 ind...
Example: If-elseif-else-end
naveedurrehman.com
r = rand
if r == 0.5
disp( 'equals indeed' )
elseif (r > 0.5)
disp( 'greate...
Repetition using For loop
naveedurrehman.com
for variable = expr
statements...
end
expr can be like: f:l or f:i:l
1. 1:10
...
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 iter...
Logical vectors
naveedurrehman.com
The elements of a logical vector are either 1
or 0. In the following example, G and H a...
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...
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 tr...
Logical vectors
naveedurrehman.com
Functions:
exist('a') %where a is a variable name
exist: is a variable exists in worksp...
Logical vectors
naveedurrehman.com
Example: calculate sixes in a dice game.
a = 1;
b = 6;
t = 500;
r = floor(a + (b-a+1).*...
Sorting
naveedurrehman.com
A vector or matrix can be sort in ascending or
descending order.
v = rand(1,10);
a = sort(v);
d...
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([...
Ordinary differential equations
naveedurrehman.com
dsolve('Dy = x*y','x')
First order ODE:
Solution:
r = dsolve('Dy = x*y'...
Ordinary differential equations
naveedurrehman.com
r = dsolve('Dy = x*y','y(1)=1','x');
x = 0:0.1:5;
y = eval(vectorize(r)...
Ordinary differential equations
naveedurrehman.com
eqn = 'D2y + 8*Dy + 2*y = cos(x)';
inits = 'y(0)=0, Dy(0)=1';
r = dsolv...
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...
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...
Example: Palindrome!
naveedurrehman.com
Ask user to input a number. Check if it is
palindrome or not.
Hint:
A palindrome n...
Example: Projectile motion
naveedurrehman.com
Ask user to enter initial velocity and angle from
horizontal for a projectil...
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...
Example: pi using Monte Carlo
naveedurrehman.com
Procedure:
1. Throw T number of darts
2. Count the number of darts fallin...
Example: pi using Monte Carlo
naveedurrehman.com
Hint:
1. Assume that radius (R) is 1 unit.
2. Generate T number of X and ...
Example: Lookup
naveedurrehman.com
Investment Profit
10 100
20 250
30 400
40 390
50 380
Find out the maximum profit and op...
Anonymous (in-line) functions
naveedurrehman.com
function_name = @(arglist)expression
Usage:
power = @(x, n) x.^n;
result1...
Anonymous (in-line) functions
naveedurrehman.com
Write an anonymous function to calculate
average of three numbers.
myavg ...
M-File functions
naveedurrehman.com
function [out1,out2, ..., outN] =
myfun(in1,in2,in3, ..., inN)
Note:
1. Functions shou...
M-File functions
naveedurrehman.com
function [sum,avg] = mysumavg(n1, n2, n3)
%This function calculates the sum and
% aver...
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…] = su...
M-File functions with subfunctions
naveedurrehman.com
Note:
1. File name should be as same as main
function’s name
2. Vari...
M-File functions with subfunctions
naveedurrehman.com
Write a function to calculate roots of a
quadratic equation. The dis...
M-File functions with nested funcs
naveedurrehman.com
function [o1,o2…] = function(in1,in2…)
….
function [o1,o2…] = nestfu...
M-File functions with nested funcs
naveedurrehman.com
Note:
1. File name should be as same as main
function’s name
2. Vari...
M-File functions with nested funcs
naveedurrehman.com
Write a function calculate roots of a
quadratic equation. The discri...
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...
THANK YOU!
Naveed ur Rehman
http://www.naveedurrehman.com/
MATLAB for Technical Computing
Upcoming SlideShare
Loading in …5
×

MATLAB for Technical Computing

956 views

Published on

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

Published in: Education
  • If you’re struggling with your assignments like me, check out ⇒ www.HelpWriting.net ⇐.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • I like this service ⇒ www.WritePaper.info ⇐ from Academic Writers. I don't have enough time write it by myself.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • The last one problem with writing is the most actual) If to speak sinceresly writing is not an easy task especially if you have no certain writing skills. That's why our company ⇒ www.HelpWriting.net ⇐ helps students to write any type of scientific papers!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

MATLAB for Technical Computing

  1. 1. MATLAB for Technical Computing Naveed ur Rehman http://www.naveedurrehman.com/
  2. 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. 3. Outline 8. Matrices and string arrays 9. Introduction to graphics 10. Loops 11. Custom functions and M-files naveedurrehman.com
  4. 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
  5. 5. Introduction An Array naveedurrehman.com Here, A is of order (m, n) = (2, 3) Element: A (1,2)
  6. 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. 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. 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. 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
  10. 10. Introduction User-interface: MATLAB Desktop naveedurrehman.com
  11. 11. 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
  12. 12. Introduction Training methodology naveedurrehman.com 1. Presentation + Code execution by Trainer in Classroom or Lab 2. Code execution + practice problems by Attendees in Lab
  13. 13. Arithmetic naveedurrehman.com Addition: 3+2 Subtraction: 3-2 Multiplication: 3*2 Division: 3/2 or 23 Exponent: 3^2
  14. 14. Arithmetic 1/0 naveedurrehman.com Infinity: inf + 3 Not-a-Number (NaN): 0/0
  15. 15. Variables naveedurrehman.com Save value in a variable: x = 3 x = 3; x Variables are case-sensitive: T = 2 t = 3 Z = t+T;
  16. 16. 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.
  17. 17. Using functions a = sqrt(4) naveedurrehman.com a = 4
  18. 18. 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)
  19. 19. Using functions naveedurrehman.com fix and rem Converting 40 inches to feet-inch. feet = fix(40/12) inches = rem(40, 12)
  20. 20. Using commands naveedurrehman.com • help function or command • clc • whos • clear • clear variable • date • calendar help sin
  21. 21. Vectors naveedurrehman.com X=[3,2] X=[3;2] Row vectors: Column vector: X= [1:10] X= [0:2:10]
  22. 22. 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
  23. 23. Vectors naveedurrehman.com X=0:180 Y = sin(X.*pi/180) Operations with functions:
  24. 24. 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.
  25. 25. Matrices naveedurrehman.com X = [1 2; 3 4] A 2D matrix: X = 1 2 3 4
  26. 26. 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:
  27. 27. Matrices naveedurrehman.com X = [1 2; 3 4] Y = [5 6; 7 8] Z = X*Y Vector operations between matrices:
  28. 28. Matrices naveedurrehman.com Y = [1 4 8; 0 -1 4]' Transpose:
  29. 29. 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.
  30. 30. Matrices naveedurrehman.com R = rand(2,3) Random matrix:
  31. 31. Arithmetic with Matrices naveedurrehman.com k = min(A) Minimum: k = max(A) Maximum: k = mean(A) Mean: k = length(A) Length:
  32. 32. Arithmetic with Matrices naveedurrehman.com k = sum(A) Sum: k = sum(A .* B) Sum of products: k = prod(A) Product:
  33. 33. Accessing elements naveedurrehman.com R = rand(5,7); a = R(1,2) b = R(1:5,2) c = R(1:4,1:3)
  34. 34. Linear equations naveedurrehman.com A = [1 2; 2 -1] B = [4; 3] R = AB Solution with matrix method:
  35. 35. Linear equations naveedurrehman.com [x,y]=solve('x+2*y=4','2*x-y=3') Solution with built-in solve function:
  36. 36. 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)
  37. 37. 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:
  38. 38. 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:
  39. 39. 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
  40. 40. Plotting naveedurrehman.com Options
  41. 41. 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+-')
  42. 42. 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
  43. 43. 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:
  44. 44. 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:
  45. 45. 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:
  46. 46. 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:
  47. 47. 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:
  48. 48. 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:
  49. 49. 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
  50. 50. Symbolic operations naveedurrehman.com a = sym('a'); b = sym('b'); c = 2*a d = 2*c+b*c
  51. 51. 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))
  52. 52. Symbolic expand and collect naveedurrehman.com Expand: syms x syms y expand((x-5)*(x+9)) expand(sin(2*x)) expand(cos(x+y))
  53. 53. 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))
  54. 54. Complex numbers naveedurrehman.com Z = 2 + 3*i Defining: Functions: R = real(Z) G = imag(Z) C = conj(Z)
  55. 55. 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
  56. 56. 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).
  57. 57. 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)])
  58. 58. 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.
  59. 59. 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.
  60. 60. Sample program: Speed naveedurrehman.com s = 20; t = 300; v = s/t; disp( 'Speed required is:' ); disp( v );
  61. 61. Sample program: SpeedS naveedurrehman.com s = 10:10:1000; t = 300; v = s./t; disp([s' v']);
  62. 62. Sample program: Balance naveedurrehman.com balance = 1000; rate = 0.09; interest = rate * balance; balance = balance + interest; disp( 'New balance:' ); disp( balance );
  63. 63. 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
  64. 64. 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:
  65. 65. Tic-toc naveedurrehman.com Tic-toc can be used for knowing execution time. tic A = input('How many apples: '); toc
  66. 66. 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.
  67. 67. 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')
  68. 68. 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).
  69. 69. 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
  70. 70. 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
  71. 71. 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
  72. 72. Example: If-end naveedurrehman.com r = rand if r > 0.5 disp( 'greater indeed' ) end 1
  73. 73. Example: If-else-end naveedurrehman.com r = rand if r > 0.5 disp( 'greater indeed' ) else disp( ‘smaller indeed' ) end 2
  74. 74. Example: If-elseif-end naveedurrehman.com r = rand if r == 0.5 disp( 'equals indeed' ) elseif (r > 0.5) disp( 'greater indeed' ) end 3
  75. 75. 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
  76. 76. 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
  77. 77. For loop: Factorial program naveedurrehman.com n = 10; fact = 1; for k = 1:n fact = k * fact; disp( [k fact] ) end
  78. 78. Repetition using While loop naveedurrehman.com while expr statements end expr is a predicate expression.
  79. 79. While loop: Numbering program naveedurrehman.com k = 1 while k < 10 disp(k); k = k + 1; end
  80. 80. Controlling in loops naveedurrehman.com 1. To terminate a loop at any iteration: break 2. To pass control to the next iteration: continue
  81. 81. 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);
  82. 82. Logical vectors naveedurrehman.com Counting true and false: R = rand(1,100); T = sum(R>0.5); F = length(R) - sum(R>0.5);
  83. 83. 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?
  84. 84. 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?
  85. 85. 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.
  86. 86. 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)
  87. 87. 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');
  88. 88. Primes and factors naveedurrehman.com primes: v = primes(100) isprime: v = isprime(97) factors: v = factor(96)
  89. 89. Evaluation of expression naveedurrehman.com Lets say: eqn = '(1/2)*x+x^2-3' Evaluation: x = 4; y = eval(eqn)
  90. 90. Vectorization of expression naveedurrehman.com Lets say: eqn = '(1/2)*x+x^2-3' Vectroization: v = vectorize(eqn);
  91. 91. 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)
  92. 92. 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:
  93. 93. 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. @
  94. 94. 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:
  95. 95. 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:
  96. 96. 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:
  97. 97. 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:
  98. 98. 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
  99. 99. 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
  100. 100. Example: Projectile motion naveedurrehman.com Range: Flight time: Max. height: Trajectory: Instant. Velocity & angle:
  101. 101. Example: Projectile motion naveedurrehman.com
  102. 102. Example: Projectile motion naveedurrehman.com
  103. 103. 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
  104. 104. 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
  105. 105. 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
  106. 106. Example: Lookup naveedurrehman.com Investment Profit 10 100 20 250 30 400 40 390 50 380 Find out the maximum profit and optimum investment.
  107. 107. 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)
  108. 108. 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)
  109. 109. 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.
  110. 110. 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:
  111. 111. M-File functions naveedurrehman.com Write a function to calculate roots of a quadratic equation.
  112. 112. M-File functions with subfunctions naveedurrehman.com function [o1,o2…] = function(in1,in2…) …. end function [o1,o2…] = subfunction(in1,in2…) …. end function.m:
  113. 113. 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
  114. 114. 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.
  115. 115. M-File functions with nested funcs naveedurrehman.com function [o1,o2…] = function(in1,in2…) …. function [o1,o2…] = nestfunction(in1,in2…) …. End … end function.m:
  116. 116. 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.
  117. 117. 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.
  118. 118. Global variables naveedurrehman.com These variables are known in all program as well as In functions.
  119. 119. 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
  120. 120. THANK YOU! Naveed ur Rehman http://www.naveedurrehman.com/

×