Matlab Solved Problems
Matlab Solved Problems
A Layman Approach
MATLAB GUI
Command Window
Workspace
Command History
[email protected]
Desktop Tools
Command Window
type commands
Workspace
view program variables
clear to clear
double click on a variable to see it in the Array Editor
Command History
view past commands
save a whole session using diary
[email protected]
Matrices
• 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
[email protected]
Matrices (Contd…)
Let, x= [ 1 2 3
5 1 4
3 2 -1]
y = x(2,3)
• x(i,j) subscription
y =
4
+ addition
- subtraction
* multiplication .* element-by-element mult
/ division ./ element-by-element div
^ power .^ element-by-element power
‘ complex conjugate .‘ transpose
transpose
[email protected]
Operators (Relational, Logical)
== equal pi 3.14159265…
~= not equal j imaginary unit, −1
< less than i same as j
<= less than or equal
> greater than
>= greater than or equal
& AND
| OR
~ NOT
[email protected]
Generating Vectors from functions
x = zeros(1,3)
• zeros(M,N) MxN matrix of zeros x =
0 0 0
[email protected]
Operators (in general)
( ) subscription x = [ 1 3 5 7 9]
x =
1 3 5 7 9
y = x(2)
y =
3
y = x(2:4)
y =
3 5 7
[email protected]
MATRIX OPERATIONS
Let, A = eye(3)
>> A = [ 1 0 0
0 1 0
0 0 1 ]
1 1 0 0 1 0 0 1 0 0
1 0 1 0 0 1 0 0 1 0
1 0 0 1 0 0 1 0 0 1
[email protected]
MATRIX OPERATIONS (Contd…)
Let, >> A = [1 2 3;4 5 6;7 8 9]
A = [ 1 2 3
4 5 6
7 8 9 ]
ans = B= C= D=
16.1168 1 4 7 14 32 50 1 8 21
-1.1168 2 5 8 32 77 122 8 25 48
-0.0000 3 6 9 50 122 194 21 48 81
[email protected]
QUESTIONS ?
[email protected]
Applications of MATLAB
(Lecture 3)
[email protected]
Overview
Linear algebra
Solving a linear equation
Finding eigenvalues and eigenvectors
[email protected]
Linear Algebra
Solving a linear system
Find the values of x, y and z for the following equations:
5x = 3y – 2z +10
8y +4z = 3x + 20
2x + 4y - 9z = 9
Step 1: Rearrange equations:
5x - 3y + 2z = 10
- 3x + 8y +4z = 20
2x + 4y - 9z = 9
Step 2: Write the equations in matrix form:
[A] x = b
5 −3 2 10
A = − 3 8 4 b = 20
2 4 − 9 9
[email protected]
Linear Algebra (Contd…)
Step 3: Solve the matrix equation in MATLAB:
>> A = [ 5 -3 2; -3 8 4; 2 4 -9];
>> b = [10; 20; 9]
>> x = A\ b
x =
3.442
3.1982
1.1868
% Veification
>> c = A*x
>> c =
10.0000
20.0000
9.0000
[email protected]
Linear Algebra (Contd…)
Finding eigenvalues and eigenvectors
Eigenvalue problem in scientific computations shows up as:
Av=λv
The problem is to find ‘λ’ and ‘v’ for a given ‘A’ so that above eq.
is satisfied:
A − λI = 0
b) Sole for ‘n’ eigenvectors by substituting the corresponding
eigenvalues in above eqn.
[email protected]
Linear Algebra (Contd…)
Method 2: By using MATLAB:
>> A = [ 5 -3 2; -3 8 4; 2 4 -9];
>> [V, D] = eig(A)
V =
-10.3463 0 0
0 4.1693 0
0 0 10.1770
[email protected]
Linear Algebra (Contd…)
[email protected]
Linear Algebra (Contd…)
Cross check:
Let us check 2nd eigenvalue and second eigenvector will
satisfy A v = λ v or not:
If you do not have a firm idea but you have data that you trust,
MATLAB can help you to explore the best possible fit.
[email protected]
Curve Fitting (Contd…)
Example 1 : straight line (linear) fit:
x 5 10 20 50 100
Y 15 33 53 140 301
[email protected]
[email protected]
[email protected]
Curve Fitting (Contd…)
Example 2 : Comparing different fits:
x = 0: pi/30 : pi/3
y = sin(x) + rand (size(x))/100
[email protected]
[email protected]
Interpolation
What is interpolation ?
x = [1 2 3 4 5 6 7 8
9]
y = [1 4 9 16 25 36 49
64 81]
Find the value of 5.5?
MATLAB Command :
>> yi=interp1(x,y,5.5,'linear')
yi = 30.5000
[email protected]
Interpolation (Contd…)
Method 2: Cubic Interpolation
MATLAB Command :
>> yi = interp1(x,y,5.5,’cubic')
yi =
30.2479
MATLAB Command :
yi =
30.2500
[email protected]
Data Analysis and statistics
As a first step, you should plot your data in the form you wish.
Then go to the figure window and select data statistics from the
tools menu.
[email protected]
Data Analysis and statistics (Contd…)
Example:
x = [1 2 3 4 5 6 7 8
9]
y = [1 4 9 16 25 36 49
64 81]
[email protected]
Data Analysis and statistics (Contd…)
[email protected]
Data Analysis and statistics (Contd…)
[email protected]
Data Analysis and statistics (Contd…)
[email protected]
Data Analysis and statistics (Contd…)
It can be performed directly by using MATLAB commands also:
Consider:
x = [1 2 3 4 5]
median (x) : gives the middle value or arithmetic mean of two middle
Numbers.
MATLAB usage: median (x) gives 3.
f(x) = 0
Example 1: Solve
sin x = e x − 5
Solution:
x= fzero('sin(x)-exp(x)+5',1)
x =
1.7878
[email protected]
Solving nonlinear algebraic equations
(contd…)
• Example 2: Solve
x2 − 2x + 4 = 0
Solution:
x= fzero(‘x*x-2*x+4',1)
xsin x== e x
−5
1.7878
[email protected]
QUESTIONS ?
[email protected]
Optimization Techniques
through MATLAB
(Lecture 4)
[email protected]
Overview
Unconstrained Optimization
Constrained Optimization
[email protected]
Why Optimize!
Engineers are always interested in finding the
‘best’ solution to the problem at hand
Fastest
Fuel Efficient
[email protected]
The Greeks started it!
Queen Dido of Carthage (7 century
BC)
– Daughter of the king of Tyre
– Agreed to buy as much land as
she could “enclose with one
bull’s hide”
– Set out to choose the largest
amount of land possible, with
one border along the sea
• A semi-circle with side
touching the ocean
• Founded Carthage
– Fell in love with Aeneas but
committed suicide when he left.
[email protected]
The Italians Countered
Joseph Louis Lagrange (1736-1813)
His work Mécanique Analytique (Analytical
Mechanics) (1788) was a mathematical
masterpiece
Invented the method of ‘variations’ which
impressed Euler and became ‘calculus of
variations’
Invented the method of multipliers
(Lagrange multipliers)
Sensitivities of the performance index to
changes in states/constraints
Became the ‘father’ of ‘Lagrangian’
Dynamics
Euler-Lagrange Equations
[email protected]
The Multi-Talented Mr. Euler
Euler (1707-1783)
Friend of Lagrange
Published a treatise which became
the de facto standard of the
‘calculus of variations’
The Method of Finding Curves
that Show Some Property of
Maximum or Minimum
He solved the brachistachrone
(brachistos = shortest, chronos =
time) problem very easily
Minimum time path for a bead
on a string, Cycloid
[email protected]
Hamilton and Jacobi
William Hamilton (1805-1865)
Inventor of the quaternion
[email protected]
What to Optimize?
Engineers intuitively know what they are
interested in optimizing
Straightforward problems
Fuel
Time
Power
Effort
More complex
Maximum margin
Minimum risk
The mathematical quantity we optimize is called
a cost function or performance index
[email protected]
Optimization through MATLAB
Consider initially the problem of finding a minimum
to the function:
min F(X)
LB <= X <= UB
[email protected]
Optimization through MATLAB
(Contd…)
[email protected]
Optimization through MATLAB
(Contd…)
X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB) defines a set of
lower and upper bounds on the design variables, X, so that the
solution is in the range LB <= X <= UB.
X=FMINCON(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON) subjects
the minimization to the constraints defined in NONLCON.
[email protected]
Unonstrained Optimization : Example
Consider the above problem with no constraints:
f ( x) = e x (4 x 2 + 2 y 2 + 4 xy + 2 y + 1)
Solution by MATLAB:
[email protected]
Unconstrained Optimization : Example
(Contd…)
>> x =
0.5000 -1.0000
>> fval =
1.3028e-010
[email protected]
Constrained Optimization : Example
Consider initially the problem of finding a minimum
to the function:
f ( x) = e x (4 x 2 + 2 y 2 + 4 xy + 2 y + 1)
Subjected to:
- x(1).x(2) < = 10
[email protected]
Constrained Optimization : Example
(contd…)
Solution using MATLAB:
function f = objfun(x)
% objective function
f=exp(x(1)) * (4*x(1)^2 + 2*x(2)^2 + 4*x(1)*x(2) +
2*x(2) + 1);
options =
optimset('LargeScale','off','Display','iter');
[x,fval,exitflag,output] =
fmincon('objfun',x0,[],[],[],[],[],[],'confun',options)
;
[email protected]
max Directional
Iter F-count f(x) constraint Step-size derivative
Procedure
1 3 1.8394 0.5 1 0.0486
2 7 1.85127 -0.09197 1 -0.556 Hessian
modified twice
3 11 0.300167 9.33 1 0.17
4 15 0.529834 0.9209 1 -0.965
5 20 0.186965 -1.517 0.5 -0.168
6 24 0.0729085 0.3313 1 -0.0518
7 28 0.0353322 -0.03303 1 -0.0142
8 32 0.0235566 0.003184 1 -6.22e-006
9 36 0.0235504 9.032e-008 1 1.76e-010 Hessian
modified
Optimization terminated successfully:
x =
-9.5474 1.0474
[email protected]
% The function value at the solution is:
fval
fval =
0.0236
c =
1.0e-014 *
0.1110
-0.1776
ceq =
[]
[email protected]
QUESTIONS ?
[email protected]
System Identification
(Lecture 5)
[email protected]
Overview
Introduction
An exciting example
[email protected]
Introduction
[email protected]
What is system identification?
[email protected]
Basic questions about system
identification (contd…)
[email protected]
Basic questions about system
identification (contd…)
[email protected]
Common terms used in system
identification
[email protected]
Common terms used in system
identification (contd…)
[email protected]
Common terms used in system
identification (contd…)
[email protected]
Basic Steps for System
Identification
[email protected]
Basic Steps for System
Identification (contd…)
[email protected]
QUESTIONS ?
[email protected]
Solution of Ordinary Differential
Equations and Engineering Computing
(Lecture 6)
[email protected]
Solution of Ordinary Differential
Equaions
[email protected]
Overview
Introduction
Examples
[email protected]
Introduction
DSOLVE Symbolic solution of ordinary differential
equations.
[email protected]
Introduction (contd…)
[email protected]
Introduction (contd…)
[email protected]
Examples
1) dsolve('Dx = -a*x') returns
ans: exp(-a*t)*C1
ans: x = exp(-a*s)
[email protected]
Examples (contd…)
[email protected]
Outline of lecture
Concept of M-files
[email protected]
MATLAB as a calculator
n
1 1 1 1
y=∑ = + + + ...
i =1 i 1 2 3
[email protected]
How to write an M-file
Run file
[email protected]
Bharani.m Version 1
[email protected]
Bharani.m Version 2
[email protected]
Decision making in MATLAB
[email protected]
Roots of ax2+bx+c=0
[email protected]
One possible M-file
Read in values of a, b, c
Calculate ∆
IF ∆ < 0
Print message ‘ No real roots’→ Go END
ELSEIF ∆ = 0
Print message ‘One real root’→ Go END
ELSE
Print message ‘Two real roots’
END
[email protected]
M-file (bharani.m)
%================================================
% Demonstration of an m-file
% Calculate the real roots of a quadratic equation
%================================================
[email protected]
M-file (bharani.m) (contd…)
% Calculate number (and value) of real roots
if delta < 0
elseif delta == 0
fprintf('\nEquation has one real root:\n')
xone = -b/(2*a)
else
fprintf('\nEquation has two real roots:\n')
x(1) = (-b + sqrt(delta))/(2*a);
x(2) = (-b – sqrt(delta))/(2*a);
fprintf('\n First root = %10.2e\n\t Second root = %10.2f',
x(1),x(2))
end
[email protected]
Conclusions
• Have reviewed:
– Concept of an M-file
– Decision making in MATLAB
– IF … END and IF … ELSEIF … ELSE … END
– Example of real roots for quadratic equation
[email protected]
QUESTIONS ?
[email protected]
Graphics
By
G Satish
Outline
2-D plots
3-D plots
Handle objects
2-D plots
Simple plot
>> a=[1 2 3 4]
>> plot(a)
Overlay plots
using plot command
>> t=0:pi/10:2*pi;
>> y=sin(t); z=cos(t);
>> plot(t,y,t,z)
Overlay plots(contd…)
using hold command
>> plot(t,sin(t));
>> grid
>> hold
>> plot(t,sin(t))
Overlay plots(contd..)
using line command
>> t=linspace(0,2*pi,10)
>> y=sin(t); y2=t; y3=(t.^3)/6+(t.^5)/120;
>> plot(t,y1)
>> line(t,y2,’linestyle’,’--’)
>> line(t,y3,’marker’,’o’)
Overlay plots
Style options
>> t=0:pi/10:2*pi;
>> y=sin(t); z=cos(t);
>>plot(t,y,’go-’,t,z,’b*--’)
Style options
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
Labels, title, legend and other text
objects
>> subplot(2,2,2)
>> semilogy(a,b);
>> grid
>> subplot(2,2,3)
>> loglog(x,exp(-x));
>> grid
Zoom in and zoom out
>> figure
>> plot(t,sin(t))
>> axis([0 2 -2 2])
Specialised plotting routines
>> stem(t,sin(t));
>> bar(t,sin(t))
>> a=[1 2 3 4]; stairs(a);
3-D plots
Simple 3-D plot
Plot of a parametric space curve
>> t=linspace(0,1,100);
>> x=t; y=t; z=t.^3;
>> plot3(x,y,z); grid
View
>> t=linspace(0,6*pi,100);
>> x=cos(t); y=sin(t); z=t;
>> subplot(2,2,1); plot3(x,y,z);
>> subplot(2,2,2); plot3(x,y,z); view(0,90);
>> subplot(2,2,3); plot3(x,y,z); view(0,0);
>> subplot(2,2,4); plot3(x,y,z); view(90,0);
View (contd…)
Mesh plots
>> x=linspace(-3,3,50);
>> [X,Y]= meshgrid(x,y);
>> Z=X.*Y.*(X.^2-Y.^2)./(X.^2+Y.^2);
>> mesh(X,Y,Z);
>> figure(2)
Mesh plots(cont…)
Surface plots
>> u = -5 : 0.2 : 5;
>> [X,Y] = meshgrid(u,u);
>> Z=cos(X).*cos(Y).*exp(-sqrt(X.^2+Y.^2)/4);
>> surf(X,Y,Z)
Surface plots (contd…)
Handle Graphics
Handle Graphics Objects
Handle Graphics is an object-oriented
structure for creating, manipulating and
displaying graphics
Graphics in Matlab consist of objects
Every graphics objects has:
– a unique identifier, called handle
– a set of characteristics, called properties
Getting object handles
There are two ways for getting object handles
• By creating handles explicitly at the object-
creation level commands
• By using explicit handle return functions
Getting object handles
By creating handles explicitly at the object-
creation level commands
>> hfig=figure
>> haxes=axes(‘position’,[0.1 0.1 0.4 0.4])
>> t=linspace(0,pi,10);
>> hL = line(t,sin(t))
>> hx1 = xlabel(‘Angle’)
Getting object handles
By using explicit handle return functions
>> gcf gets the handle of the current
figure
>> gca gets handle of current axes
>> gco returns the current object in the
current figure
Getting object handles
Example
>> figure
>> axes
>> line([1 2 3 4],[1 2 3 4])
>> hfig = gcf
>> haxes = gca
Click on the line in figure
>>hL=gco
Getting properties of objects
The function ‘get’ is used to get a property
value of an object specified by its handle
get(handle,’PropertyName’)
The following command will get a list of all
property names and their current values of an
object with handle h
get(h)
Getting properties of objects
Example
>> h1=plot([ 1 2 3 4]);returns a line
object
>> get(h1)
>> get(h1,’type’)
>> get(h1,’linestyle’)
Setting properties of objects
The properties of the objects can be set by
using ‘set’ command which has the following
command form
Set(handle, ‘PropertyName’,Propertyvalue’)
By using following command you can see the
the list of properties and their values
Set(handle)
Setting properties of objects
example
>> t=linspace(0,pi,50);
>> x=t.*sin(t);
>> hL=line(t,x);
Setting properties of objects
>> set(hL,’linestyle’,’--’);
Setting properties of objects
>> set(hL,’linewidth’,3,’marker’,’o’)
Setting properties of objects
>> yvec = get(hL,’ydata’);
>> yvec(15:20) = 0;
>> yvec(40:45) = 0;
>> set(hL, ’ydata’, yvec)
Creating subplots using axes
command
>> hfig=figure
>> ha1=axes(‘position’,[0.1 0.5 0.3 0.3])
>> line([1 2 3 4],[1 2 3 4])