Matlab-01
Matlab-01
Lesson 2: Creating and working with arrays and numbers [Page 14- 22]
LESSON 01
INTRUDUCTION
What is MATLAB ?
Application in Mathematics:
MATLAB built in function provides excellent tolls for linear algebra computations,
data analysis, optimization numerical solution of ordinary differential equation
(ODE’S) quadrature and many other types of scientific computations.
There is numerous functions for 2-D and 3-D graphics as well as for animation.
Also for those who cannot do with their FORTRAN and or C codes.
2
Goal: To learn how to open MATLAB, do a few trivial calculation, quit MATLAB.
>> 2+3
ans =
>> x=2;
>> y=3;
>> x+y
ans =
More example :
>> y=2^2+log(pi)*sin(x)
y=
5.0409 .
3
*** Compute and
>> 2^5/(2^5-1)
ans =
1.0323
>> (1-1/2^5)^(-1)
ans =
1.0323
>> r=((pi)^1/3)-1;
>> A=pi*r^2
A=
0.0070
i) e3
>> exp(3)
ans =
4
20.085 .
ii) ln(e3)
>> log(exp(3))
ans =
iii) log(105)
>> log10(10^5)
ans =
Trigonometry :
***Compute sinП/6
>> sin(pi)/6
ans =
2.0411e-017
***Compute tanП/2
>> tan(pi)/2
ans =
5
-6.1232e-017
>> (sin(pi)/6)^2+(cos(pi)/6)^2
ans =
0.0278
>> x=32*pi;
>> y=(cosh(x))^2-sinh(x)
y=
5.2243e+086
iП/4 .
*** By using Euler’s Theorem compute e
>> (cos(pi/4))+i*sin(pi)/4
ans =
0.7071 + 0.7071i
6
LESSON 02
CREATING AND WORKING WITH ARRAYS AND NUMBERS
Array :
An Array is a list of numbers or expressions arranged in horizontal rows and
vertical columns .
When an array has only one row or column then it’s called vector .
An array with m rows and n columns is called a matrix of size m×n.
Goal:
To learn how to create Arrays and Vectors and how to perform Arithmetic and
Trigonometric operations on them .
>> x =[ 1 2 3 ]
x=
1 2 3
7
>> y=[1;3;5]
y=
1
3
5
>> x=linspace(0,10,5);
>> y=sin(x)
y=
>> x=linspace(10,100,50);
>> y=sqrt(x).*sin(x)
y=
Columns 1 through 16
Columns 17 through 32
8
Columns 33 through 48
Columns 49 through 50
-6.9248 -5.0637
y=
.
***Create a vector t with 10 elements 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Now
compute the following quantities.
i) x = t sint
ii) y =(t-1) / (t+1)
iii) z = sint2 /t2
>> t=linspace(1,10,10);
>> x= t.*sin(t)
x=
9
0.8415 1.8186 0.4234 -3.0272 -4.7946 -1.6765 4.5989 7.9149
3.7091 -5.4402
>> y=(t-1)./(t+1)
y=
>> z=sin(t.^2)./(t.^2)
z=
Points on a Circle:
All points with co-ordinates x = rcosØ and y=rsinØ ,where r is a constant ,lie on a
circle with radiuser . i .e they satisfy the equation , x2 + y2 = r2
Create a column vector for Ø with the values : 0 , П/4 , П /2 , 3П /4 , П , and
5П/4.
Take r =2 and compute the column vector x and y .now check that x and y indeed
satisfy the equation of circle by computing the radius r = √(x2 +y2) .
>> theata=[0;pi/4;pi/2;3*pi/4;pi;5*pi/4 ];
10
>> r=2;
>> x=r*cos(theta);
>> y=r*sin(theta);
>> r=sqrt(x.^2+y.^2)
r=
2
2
2
.
.
.
2
Geomatric Series :
The sum of a geometric series 1+r+r2+r3+………..+rn approaches the limit 1/1-r for
r < 1 as n→∞ .
i) Create a vector n of 11 elements from 0— 10 .
ii) Take r = 0.5 and create another vector x =[r0 r1 r2 ………..rn ] .
iii) Now take the sum of the vector with the command S =sum(x) .
iv) Calculate the limits 1/1-r and compare the computed sum s .
>> n=linspace(0,10,11);
r=0.5;
x=r.^n;
S= sum(x)
S=
1.9990
>> P=1/(1-r)
P=
11
There is a little difference between S and P. So we can avoid it.
LESSON 03
CREATING AND PRINTING SIMPLE PLOTS
Goal:
To learn how to make a simple 2-D plot in MATLAB and print it out.
Problems:
*** Draw a circle of Unit radius.
r=1;
theta=linspace(0,2*pi,100);
x=r.*cos(theta);
y=r.*sin(theta);
plot(x,y,0,0,'+')
axis('equal')
xlabel('x')
ylabel('y')
title('Unit circle')
13
***A simple sin pliot: Plot y=sinx, 0≤x≤2 , taking 100 linealy
spaced points in the given interval. Label the axes and put “Plot
created by yourname” in the title.
>> x=linspace(0,2*pi,100);
>> y=sin(x);
>> plot(x,y)
>> xlabel('x')
>> ylabel('y')
>> title('Paavel’)
14
Line-styles:
***Make the same plot as above, but rather than displaying the graph as a
curve, show the unconnected data points. To display the data points with
small circles, use plot( x,y,’o’ ).
>> x=linspace(0,2*pi,100);
>> y=sin(x);
>> plot(x,y,'o')
>> xlabel('x')
>> ylabel('y')
>> title('Line Style')
15
***An exponentially decaying sin plot: Plot y= sinx, 0≤x≤4x,
taking 100 points in the interval.
>> x=linspace(0,4*pi,100);
>> y=exp(-0.4*x).*sin(x);
>> plot(x,y)
>> xlabel('x')
>> ylabel('y')
>> title('exponentially decying sine plot')
16
***Use the command plot3(x,y,z) to plot the circular helix.
x(t)=sint
y(t)=cost 0 ≤t ≤20
z(t)=t
t=linspace(0,20,20);
x=sin(t);
y=cos(t);
z=t;
plot3(x,y,z)
xlabel('x')
ylabel('y')
title('plot3')
17
Overlay plots:
Plot y=cosx and for 0≤x≤pi.
x=linspace(0,pi,100);
y=cos(x);
z=1-x.^2/2+x.^4/4;
plot(x,y,x,z)
plot(x,y,x,z,'--')
xlabel('x')
ylabel('y')
title('ZAHID')
legend('cos(x)','z')
18
LESSON 04
MATRIX AND VECTOR
19
Input: A matrix is interted row-wise with consecutive elements of a row
separated by a space or a comma and the rows separated by semicolons. The
entire matrix be enclused within square brackets.
Indexing:
A(I,j) Refers to the elements aij of the matrix A.
A(m:n,k:l) Specifies rows m to n and columns k to l of matrix A.
A(:,5:20) Refers to the elements in columns 5 through 20 of all rows of
matrix A.
A(2:10,:) Refers to the elements in rows 5 through 20 of all columns of
matrix A.
Appending a Row or Column:
A=[A U] Appends the Column vector U to the column of A.
A=[A; V] Appends the row vector V to the rows of A.
Note: A row or Column of any size may be appended to null vector.
Deleting a Row or Column: Any rows or columns of a martix can be deleted by
setting the row or column to a null vector.
A(2,:)=[ ] Delete the second row of a Matrix A.
A(:,3)=[ ] Delete the third column of a Matrix A.
A(:,3:5)=[ ] Delete the third to fifth column of a Matrix A.
A([1 3],:)=[ ] Delete the 1st and 3rd rows of a Matrix A.
Reshaping Matrix:
reshape(A,p,q) A m*n matrix ‘A’ will be reshape into a p*q matrix as long as
m*n=p*q.
b=A(:) All the elements of matrix A will be strung into a single column vector
b.
Transpose:
B=A’ Produces the transpose of matrix A.
Utility:
eye(m,n) Returns an m*n matrix with 1 on the main diagonal.
zeros(m,n) Returns an m*n matrix with zeros.
ones(m,n) Returns an m*n matrix of ones.
20
rand(m,n) Returns an m*n matrix of random numbers.
diag(v) Generates a diagonal matrix with vector v on the diagonal.
diag(A) Extracts the diagonal of matrix A as a vector.
Tril(A) Extracts the lower triangular part of matrix A.
Triu(A) Extracts the upper triangular part of matrix A.
Note: eye(m)/zeros(m) e.t.c produce m*m square matrix.
Problem 01
***Enter the matrix A= 1 2 3
4 5 6
7 8 9
A=
1 2 3
4 5 6
7 8 9
>> A(2,3)
ans =
>> A(3,1)
21
ans =
>> A(3,3)=9
A=
1 2 3
4 5 6
7 8 9
>> A(2:3,1:3)
ans =
4 5 6
7 8 9
>> A(2:3,:)
ans =
4 5 6
7 8 9
Problem 02
*** If A= 1 0 0
1 0 0
0 0 1
U=[5 6 7 ]
V= 2
3
4
A=
1 0 0
0 1 0
0 0 1
5 6 7
>> A=[1 0 0;0 1 0;0 0 1];
>> A=[A V]
A=
1 0 0 2
0 1 0 3
0 0 1 4
>> A=[1 0 0;0 1 0;0 0 1];
>> A=[A U']
A=
1 0 0 5
0 1 0 6
0 0 1 7
Yes. A=[A U] produce an error because we know that when we add a row vector
with a same size matrix we have to use a semicolon between them.
Problem 03:
Create a null matrix then appends a row vector of size 3.
A=[ ]
A=
[]
B=[5 6 7]
B=
5 6 7
23
>> A=[A;B]
A=
5 6 7
Problem 04:
Create the following martices with the help of generation function
zeros,eye,ones.
D= 0 0 0
0 0 0
0 0 0
E= 5 0 0
0 5 0
0 0 5
F= 3 3
3 3
Solution:
>> D=zeros(3,3)
D=
0 0 0
0 0 0
0 0 0
>> E=5*eye(3)
E=
5 0 0
0 5 0
0 0 5
>> F=3*ones(2,2)
24
F=
3 3
3 3
LESSON 05
MARTIX AND ARRAY OPERATIONS
Priliminary Discussion:
A+B or A-B is valid if matrix A and B are the same size.
A*B is valid if the rows number of matrix A be the equal of the columns
number of matrix B.
A/B is valid for same size square matrix A and B.
A^2 is valid if a is a square matrix.
25
Matrix Function:
exp(A) Produce a matrix with elements e(Aij).
log(A) Produce a matrix with elements ln(Aij).
log10(A) Produce a matrix with elements log10(Aij).
sqrt(A) Produce a matrix with elements rootover of Aij.
expm(A) Find eA.
logm(A) Find e log(A).
sqrtm(A) Find root A.
det(A) Find determinant of A.
inv(A) Find inverse of A.
eig(A) Find eigen values of A in a column vector.
*eigvec,eigval+=eig(A) Finds the eigenvectors of A in the matrix ‘eigvec’ and
the eigen values of A on the diagonal of the matrix ‘eigval’.
3.4442
3.1982
1.1868
By finding Inverse:
>>A=[5 -3 2;-3 8 4;2 4 -9];
>> b=[10;20;9];
X=inv(A)*b
26
X=
3.4442
3.1982
1.1868
By using Cramers Rule:
>> A=[5 -3 2;-3 8 4;2 4 -9];
>> A1=[10 -3 2;20 8 4;9 4 -9];
>> A2=[5 10 2;-3 20 4;2 9 -9];
>> A3=[5 -3 10;-3 8 20;2 4 9];
>> x=det(A1)/det(A)
x=
3.4442
>> y=det(A2)/det(A)
y=
3.1982
>> z=det(A3)/det(A)
z=
1.1868
Gassisan Elimination Method:
>> A=[5 -3 2;-3 8 4;2 4 -9];
>> b=[10;20;9];
>> C=[A b]
C=
5 -3 2 10
-3 8 4 20
2 4 -9 9
>> Cr=rref(C)
Cr =
1.0000 0 0 3.4442
27
0 1.0000 0 3.1982
0 0 1.0000 1.1868
Problem 02:
If A= 4 1 -1
2 5 -2
1 1 2
then write down the command to find the eigen values and eigen vectors of A.
Also verify the Cayley-Hamilton theorem.
Solution:
>> A=[4 1 -1;2 5 -2;1 1 2];
>> [V,D]=eig(A)
V=
D=
5.0000 0 0
0 3.0000 0
0 0 3.0000
>> P=poly(A)
P=
>> A^3-11*A^2+39*A-45*eye(3)
ans =
0 0 0
0 0 0
0 0 0
28
LESSON 06
GRAPHICS(2-D & 3-D PLOTS)
MATLAB. includes good tools for visualizatioin. Basic 2-D plots, fancy 3-D graphics
with lighting and colourmaps, complete user control of the graphics objects
through Handle graphics, tools for desinging sophisticated graphics user interface
and animation are now part of MATLAB.
The most basic and perhaps most useful comannds are:
plot(x,y) Plot y vs x with a solid line.
plot(x,y,’--‘) Plot y vs x with a dashed line.
plot(x) Plots the elements of x aginst their row index.
Style Option:
The style option in the plot command is character string that consists of 1,2 or
character that specify the colour and/or the line style. There are color, line and
marker style option.
29
Color Style Option Line Style option Marker Style Option
The line style option is made up of either the color option, the line style option or
a combination of the tow.
Examples:
Plot(x,y,’r’) Plot y vs x with a red solid line.
Plot(x,y,’:’) Plot y vs x with a dotted line.
Plot(x,y,’b--’) Plot y vs x with a blue dashed line.
Plot(x,y,’+’) Plot y vs x as connected points marked by +
Labels, title, legend and other text objects:
legend(string1,string2,…) Produces legend using the text in string1, string2
e.t.c as labels.
xlabel(‘X axis’) Labels the x-axis with X axis.
ylabel(‘Y axis’) Labels the y-axis with Y axis.
title(‘Graph of Sinx’) Titles the plot with Graph of Sinx.
text(x,y,’text’) Writes ‘text’ at the location (x,y) is the plot co-ordinates.
Legend off Deletes the legend from the plot.
Axes Control:
Once a plot is generated the axis limit can change with the axis command.
Axis([xmin xmax ymin ymax]) Changes the current axes limits to the
specified new values xmin and xmax for the x-axis and ymin and ymax for the y-
axis.
Overlay Plots:
30
There are three different ways of generating overlay plots in MATLAB: the plot,
hold and the line commands.
Problem 01:
***Plot y1=sint, y2=t and y3=t-
Method 01 (Using the plot command to generate overlay plots)
>> t=linspace(0,2*pi,100);
>> y1=sin(t);
>> y2=t;
>> y3=t-(t.^3)/6+(t.^5)/120;
>> plot(t,y1,t,y2,'--',t,y3,'o')
>> axis([0 5 -1 5])
>> xlabel('t')
>> ylabel('Approximation of sin(t)')
>> title('Fun with sin(t)')
>> text(3.5,0,'sin(t)')
>> gtext('Linear Approximation')
>> gtext('First 3 terms')
>> gtext('in Taylor series')
31
Method 02 (Using the hold command to generate overlay plots):
x=linspace(0,2*pi,100);
y1=sin(x);
plot(x,y1)
hold on
y2=x;
32
plot(x,y2,'--')
y3=x-(x.^3)/6+(x.^5)/120;
plot(x,y3,'o')
axis([0 5 -1 5])
xlabel('t')
ylabel('Approximation of sin(t)')
title('Fun with sin(t)')
legend('y1','y2','y3')
hold off
33
Method 03 (Using the line command to generate overlay plots)
>> t=linspace(0,2*pi,100);
>> y1=sin(t);
>>y2=t;
>>y3=t-(t.^3)/6+(t.^5)/120;
>> plot(t,y1)
>> line(t,y2,'linestyle','--')
>> line(t,y3,'marker','o')
Problem 02:
***Plot f(t)=t sint, 0≤t≤10∏
>> fplot('t.*sin(t)',[0 10*pi])
34
Problem 02:
***If x= , y=t , 0 ≤t ≤2∏ then make semilog plot with log scale on the x-axis.
>> t=linspace(0,2*pi,100);
>> x=exp(-t);
>> y=t;
>> semilogx(x,y),grid
35
Problem 03:
***If x=t, y= , 0 ≤t ≤2∏ then make semilog plot with log scale on the y-axis.
>> t=linspace(0,2*pi,100);
>>x=t;
>>y=exp(t);
>>semilogy(x,y),grid
36
Problem 03:
***If x= , y=100+ ,0 ≤t ≤2∏ then create plot with log scale.
>> t=linspace(0,2*pi,100);
>> x=exp(t);
>> y=100+exp(2*t);
>> loglog(x,y),grid
37
Problem 03:
***If =2sin5t, 0≤t≤2∏ then plot it by polar command.
>> t=linspace(0,2*pi,100);
>> r=sqrt(abs(2*sin(5*t)));
>> polar(t,r)
38
Problem 04:
***If =2sin5t, 0≤t≤2∏, x=rcost, y=rsint then plot it by polar command.
>> t=linspace(0,2*pi,500);
>>r=sqrt(abs(2*sin(5*t)));
>>x=r.*cos(t);
>>y=r.*sin(t);
>>fill(x,y,'r')
>>axis('square')
39
Problem 04:
***If =2sin5t, 0≤t≤2∏, x=rcost, y=rsint then plot it with bar diagram.
>> t=linspace(0,2*pi,500);
>>r=sqrt(abs(2*sin(5*t)));
>>y=r.*sin(t);
>>bar(t,y)
>> axis([0 pi 0 inf])
40
Problem 05:
***If five continents are Asia, Europe, Africa, N. America, S. America and their
Population is 3332, 669, 1239, 307, 500 respectively in 1992 (in millions), then
show them in Bar diagram.
>> cont=char('Asia','Europe','Africa','N. America','S. America');
>> pop=[3332;669;1239;307;500];
>> barh(pop)
>> for i=1:5
gtext(cont(i,:));
end
>> xlabel('population in millions')
>> ylabel('Continents')
>> title('World population (1992)')
41
In Pie Diagram
>> cont=char('Asia','Europe','Africa','N. America','S. America');
>>pop=[3332;669;1239;307;500];
>>pie(pop)
>>for i=1:5
gtext(cont(i,:));
end
>>xlabel('population in millions')
>>ylabel('Continents')
>>title('World population (1992)')
42
Problem 06:
***If y=tsint, 0≤t≤10∏ then plot it by comet command.
>> t=linspace(0,10*pi,200);
y=t.*sin(t);
comet(x,y)
43
Problem 07:
*** Plot in 3-Dimension x(t)=t, y(t)= , z(t)= , 0 ≤ t ≤ 1.
>> t=linspace(0,1,200);
>> x=t;
>> y=t.^2;
>> z=t.^3;
>> plot3(x,y,z),grid
44
Problem 08:
*** Plot cosx.cosy. , ∣x∣≤5, ∣y∣≤5
>> u=-5:.2:5;
>> [x,y]=meshgrid(u,u);
>> z=cos(x).*cos(y).*exp(-sqrt(x.^2+y.^2)/4);
>> surf(x,y,z)
45
Problem 08:
*** Plot z= , ∣x∣≤3, ∣y∣≤3
>> x=linspace(-3,3,50);
>> y=x;
>> [x,y]=meshgrid(x,y);
>> z=-5./(1+x.^2+y.^2);
>> waterfall(z)
>> hidden off
46
LESSON 07
CALCULAS
47
Mathematical Operation MATLAB
limit(f)
limit(f,x,a)
limit(f,x,a,’left’)
limit(f,x,a,’right’)
Problems:
***Find
>> syms x
>>LHL= limit(x/abs(x),x,0,'left')
LHL =
-1
>> RHL=limit(x/abs(x),x,0,'right')
RHL =
48
*** Test whether the limit of at x=o exist or not.
>> LHL=limit(1/x,x,0,'left')
LHL =
-Inf
>> RHL=limit(1/x,x,0,'right')
RHL =
Inf
Since LHL≠RHL, so limit does not exist.
*** Find
>> LHL=limit((x+cos(x))/x,x,inf,'left')
LHL =
>> RHL=limit((x+cos(x))/x,x,inf,'right')
RHL =
>> limit((x+cos(x))/x,x,inf)
49
ans =
LHL =
>> RHL=limit(x^2+2,x,1,'right')
RHL =
3
Since LHL≠RHL, so limit does not exist.
*** Afunc
At x=o
>> LHL=limit(x^2+1,x,0,'left')
LHL =
>> LHL=limit(x,x,0,'right')
RHL =
0
Since LHL≠RHL, so limit does not exist.
At x=1
50
>> LHL=limit(x,x,1,'left')
LHL =
>> RHL=limit(1/x,x,1,'right')
RHL =
1
Since LHL=RHL=2 so limit =2
Condition of be Continuous
Derivative
Mathematical Operation MATLAB
f’(x) limit((f(x+h)-f(x))/h,h,o)
f’’(x) limit((f(x+h)-2*f(x)+f(x+h))/h^2,h,0)
51
*** Find the first derivative of cosx
>> syms x h
>> limit((cos(x+h)-cos(x))/h,h,0)
ans =
-sin(x)
ans =
(-125)*cos(5*x)
ans =
0
Partial Derivative (Several veriables)
*** Find the derivative of Sin(s*t)
>> syms s t
>> f=sin(s*t)
f=
sin(s*t)
>> diff(f,t)
52
ans =
s*cos(s*t)
>> diff(f,s)
ans =
t*cos(s*t)
ans =
a*cos(a*x)
Integration:
Matheamtical Operation MATLAB Command
∫ dx int(x^n,x)
∫ dx int(f,x)
∫ dx int(f,x,a,b)
int(1/1+cos(x),x)
∫
53
ans =
-cos(5*x)/5
***Find ∫ dx
>> syms x
>> int(2+x,x,0,2)
ans =
LESSON 08
DIFFERENTIAL EQUATION
54
Normal MATLAB
D
D2
Dy
D2y
Problems:
***Solve it with MATLAB command
>> dsolve('Dy=1+y^2')
ans =
i
-i
tan(C3 + t)
>>dsolve('D2y+4*y=exp(-2*x)','y(0)=0','Dy(pi)=0','x')
ans =
clear all;
close all;
dsolve('Dy=-x/y','y(4)=3','x');
clear all;
close all;
x=linspace(0,10,100);
y=-(x.^2+25).^(1/2);
55
plot(x,y)
56