3rdyear Lab MATLAB 2019 PDF
3rdyear Lab MATLAB 2019 PDF
FORTRAN:
real*8 A(10,10), B(10,10), C(10,10)
do i=1,10
do j=1,10
C(i,j) = A(i,j) + B(i,j)
end do
end do
MATLAB:
C=A+B
MATLAB Introduction
MATLAB is available for MS Windows,
Macintosh personal computer, Unix and other
operating systems.
Disadvantages
• It uses a large amount of memory and on slow computers it
is very hard to use.
• It is very Expensive software.
MATLAB WINDOWS
Command Window
type commands
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
– view past commands
– save a whole session
using diary
MATLAB
Command
Window
MATLAB WINDOWS
Command Window:
The Command Window is MATLAB’s main window and opens
when MATLAB is started. It is convenient to have the Command
Window as the only visible window, and this can be done by either
closing all the other windows (click on the x at the top right-hand
side of the window you want to close) or by first selecting the
Desktop Layout in the Desktop menu, and then selecting Command
Window Only from the submenu that opens.
Figure Window:
The Figure Window opens automatically when graphics commands
are executed, and contains graphs created by these commands
MATLAB WINDOWS
Editor Window:
The Editor Window is used for writing and editing programs.
This window is opened from the File menu.
Help Window:
>> 27^(1/3)+32^0.2
1/3 is executed first, 27^(1/3) and 32^0.2 are executed
next, and + is executed last.
>> 0.7854-(0.7854)^3/(1*2*3)+0.785^5/(1*2*3*4*5)...
-(0.785)^7/(1*2*3*4*5*6*7)
Type three periods ... (and press Enter) to continue the
expression on the next line.
Using Help in Matlab
Online help is available from the Matlab prompt (>> a double
arrow)
>> helpwin
[a long list of help topics follows]
>> helpwin fminsearch
[a help message on the fminsearch function follows].
>>doc plot
[displays the HTML documentation for the MATLAB function
plot].
>> type norminv
[display brief information of the non-built-in function norminv]
>> lookfor cdf
>> demo
Operators (arithmetic)
For scalars, the left division is the inverse of the right division. The
left division, however, is mostly used for operations with arrays.
Order of Precedence
2nd 1st
38
Changing Matrix Elements
NOTE: Unless you are overwriting with a single value the data entered
must be of the same size as the matrix part to be overwritten.
Accessing Multiple Rows, Columns
– Multiple Rows:
>> Variable_Name(start:end, :)
– Multiple Columns:
>> Variable_Name(:, start:end)
44
Accessing Multiple Rows, Columns
A(:,n) Refers to the elements in all the rows of column n of
the matrix A.
A(n,:) Refers to the elements in all the columns of row n of
the matrix A.
A(:,m:n) Refers to the elements in all the rows between
columns m and n of the
matrix A.
A(m:n,:) Refers to the elements in all the columns between
rows m and n of the
matrix A.
A(m:n,p:q) Refers to the elements in rows m through n and
columns p through q of the matrix A.
Accessing Multiple Rows, Columns
– Multiple Rows:
>>Variable_Name([index1, index2, etc.], :)
– Multiple Columns:
>>Variable_Name(:, [index1, index2, etc.])
B = A([1,3],[1,3,5:7])
Refers reate a matrix B from the 1st and 3rd rows, and 1st,
3rd, and the 5th through 7th columns of A.
46
Changing Multiple Rows, Columns
47
The colon operator
.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
The use of “.” – “Element”
A = [1 2 3; 5 1 4; 3 2 1] Operation
A=
1 2 3
5 1 4
3 2 -1
b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
Inner Product (*)
Xb=inv(A)*B
Create a sparse 5 x 4 matrix S having only 3 non–zero
values: S1,2 = 10, S3,3 = 11 and S5,4 = 12.
Think about what would be produced by the following sequence of
statements and expressions, and then type them to verify your answers.
i) m = [1:4; 3 11 7 2] ii) m(2,3) iii) m(:,3) iv) m(4) v) size(m)
vi) mat(:,2) = [ ] vii) vec = m(1,:) viii) vec(2) = 5 ix) vec(3) = [ ]
x) vec(5) = 8 xi) vec = [vec 11]
EXAMPLE OF A 2-D PLOT Legend
Plot title
Light Intensity as a Function of Distance
1200
Theory
y axis Experiment
label 1000
Text
Tick-mark
800
INTENSITY (lux)
600
400
Data symbol
200
0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
The basic 2-D plot command is
plot(x,y)
plot(x,y,’line specifiers’)
LINE SPECIFIERS IN THE plot() COMMAND
plot(x,y,’line specifiers’)
Table of line specifiers Options
S Color S Data S Line
Symbol Type
TITLE LEGEND
TEXT
or
GTEXT
YLABEL
XLABEL
PLOT OF GIVEN DATA USING LINE
SPECIFIERS IN THE plot() COMMAND
Line Specifiers:
dashed red line and asterisk
markers.
PLOT OF GIVEN DATA USING LINE
SPECIFIERS IN THE plot() COMMAND
fontsize (14)
sin(10πt)
cos(10πt)
»plot2d_soln
Subplots
SUBPLOT- display multiple axes in the same figure window
subplot(#rows, #cols, index)
»subplot(2,2,1);
»plot(1:10)
»subplot(2,2,2)
»x = 0:.1:2*pi;
»plot(x,sin(x))
»subplot(2,2,3)
»x = 0:.1:2*pi;
»plot(x,exp(-x),’r’)
»subplot(2,2,4)
»plot(peaks)
»subplotex
Alternative Scales for Axes
LOGLOG SEMILOGY
Both axes log Y
logarithmic linear X
SEMILOGX PLOTYY
log X 2 sets of
linear Y linear axes
»other_axes
CREATING A PLOT OF A FUNCTION
−0.5 x
Consider: y = 3.5 cos(6 x) for − 2 ≤ x ≤ 4
A script file for plotting the function is:
% A script file that creates a plot of
% the function: 3.5^(-0.5x)*cos(6x)
x = [-2:0.01:4]; Creating a vector with spacing of 0.01.
y = 3.5.^(-0.5*x).*cos(6*x);
Calculating a value of y
plot(x,y) for each x.
x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
THE fplot COMMAND
fplot(‘function’,limits)
The limits is a vector with the domain of x, and optionally with limits
of the y axis:
[xmin,xmax] or [xmin,xmax,ymin,ymax]
plot(x,y,u,v,t,h)
The curves can have a specific style by adding specifiers after each
pair, for example:
plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT
120
100
80
60
40
20
-20
-40
-2 -1 0 1 2 3 4
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
hold on Holds the current plot and all axis properties so that
subsequent plot commands add to the existing plot.
hold off Returns to the default mode whereby plot commands erase
the previous plots and reset all axis properties before
drawing new plots.
This method is useful when all the information (vectors) used for the
plotting is not available a the same time.
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
Plot of the function, y = 3 x 3 − 26 x + 10 and its first and second
derivatives, for − 2 ≤ x ≤ 4 all in the same plot.
x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b')
First graph is created.
hold on
plot(x,yd,'--r')
plot(x,ydd,':k') Two more graphs are created.
hold off
EXAMPLE OF A FORMATTED 2-D PLOT
Plot title
Light Intensity as a Function of Distance
1200 Legend
Theory
y axis Experiment
label 1000
Text
Tick-mark
800
INTENSITY (lux)
600
400
Data symbol
200
0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
FORMATTING PLOTS
1. Formatting commands.
In this method commands, that make changes or
additions to the plot, are entered after the plot()
command. This can be done in the Command Window,
or as part of a program in a script file.
title(‘string’)
Adds the string as a title at the top of the plot.
xlabel(‘string’)
Adds the string as a label to the x-axis.
ylabel(‘string’)
Adds the string as a label to the y-axis.
legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when
several curves are in one plot). The location of the legend is
specified by the mouse.
text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to
the plot axes.
gtext(‘string’)
Places the string (text) on the plot. When the command
executes the figure window pops and the text location is clicked
with the mouse.
EXAMPLE OF A FORMATTED PLOT
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
-3 -2 -1 0 1 2 3
x = -2.9:0.2:2.9;
bar(x,exp(-x.*x));
98
What kind of graphics is possible in Matlab?
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Line plot:
x=0:0.05:5;y=sin(x.^2);plot(x,y);
99
What kind of graphics is possible in Matlab?
0.35
0.3
0.25
0.2
0.15
0.1
0.05
-0.05
-0.1
-0.15
0 0.5 1 1.5 2 2.5 3 3.5 4
Stem plot:
x = 0:0.1:4;, y = sin(x.^2).*exp(-x);
stem(x,y)
100
What kind of graphics is possible in Matlab?
10
-5
-10
30
25
20
20
15
10 10
5
0 0
101
What kind of graphics is possible in Matlab?
10
-5
-10
30
25
20
20
15
10 10
5
0 0
Surface plot:
z=peaks(25);, surf(z);, colormap(jet);
102
What kind of graphics is possible in Matlab?
25
20
15
10
5 10 15 20 25
103
Conditional Statements + Loops
CONDITIONAL STATEMENTS
Conditional statements enable MATLAB to make decisions.
The process is similar to the way we (humans) make decisions.
A condition stated. If the condition is met, one set of actions is taken. If the
condition is not met, either nothing is done, or a second set of actions is taken.
Example:
If I win the Lottery,
•I will quit college, buy a new car, and go fishing.
If I do not win the Lottery,
•I will study harder so that I can get a better job.
If Statement (In real life)
condition
If logical expression False
statements True
end Statement
If Statement (Example)
a <= 30
If a <= 30 False
total = 2*a True
a <= 30
If a <= 30
True False
total = 2*a
else total = 2*a total = a+10
total = a + 10
end
Nested Logic - I (In real life)
False
condition1
If logical expression 1
True
statement group 1
Statement1
If logical expression 2
Statement group 2 False
condition2
end
end True
Statement2
Nested Logic – I (Example)
False
a <= 30
If a <= 30
c = a + 10 True
If c <= 12 c = a + 10
c=0 False
end c <= 12
end True
c=0
Nested Logic – II (In real life)
condition1 False
True
If logical expression 1
statement group 1 condition2
elseif logical expression 2 Statement1 True False
statement group 2
else Statement2 Statement3
statement group 3
end
Nested Logic – II (Example)
a <= 30 False
True
If a <= 30
c=a*2 c >= 20
elseif c >= 20 c=a*2 True False
d=c
else d=c d=0
d=0
end
USING THE if–elseif-else-end STATEMENT
Write program that calculates tip based on amount of bill, using the
following rules
If
bill < $10 False
• Bill less than $10
True
• Tip is $1.80
ElseIf False
• Bill between $10 and $60
$10 < bill < $60
• Tip is %18 Else
• Bill above $60 tip = $1.80 True
End
USING THE if–elseif-else-end STATEMENT
%Do stuff
if input > 0
fprintf(‘Greater than 0’)
elseif input < 0
fprintf(‘Less than 0’)
else
fprintf(‘Equals Zero’)
end
120
Write an if construct that will assign the grades as
previously described using (a) multiple elseif clauses
and (b) nested if constructs.
Increment variable by s
for loops (Example)
a=1
for a = 1:2:10
True
total = total + a a > 10
end
False
total = total +a
a=a+2
for loops
for loop variable = m:s:n
statements
end
Note:
126
w hile loops
initialize k
128
Nested loops
for index1 = array1 for index1 = array1
statement1;
statement1; statement2;
statement2; while expression
for index2 = array2 statement3;
statement3; statement4;
if expression1
statement4; statement5;
end end
end end
end
Anywhere
return – returns control to the
command line (or to the calling
function).
130
Problem
The following were the daily maximum temperatures (in F) in
Washington, DC, during the month of April 2002: 58 73 73 53
50 48 56 73 73 66 69 63 74 82 84 91 93 89 91 80 59 69 56 64 63
66 64 74 63 69 (data from the U.S. National Oceanic and
Atmospheric Administration). Use relational and logical
operations to determine the following:
(a) The number of days the temperature was above 75 .
(b) The number of days the temperature was between 65 and 80 .
(c) The days of the month when the temperature was between 50
and 60 .
131
Problem
A worker is paid according to his hourly wage up to 40 hours,
and 50% more for overtime. Write a program in a script file that
calculates the pay to a worker. The program asks the user to
enter the number of hours and the hourly wage. The program
then displays the pay.
132
Problem
A vector is given by
V = [5, 17, –3, 8, 0, –7, 12, 15, 20, –6, 6, 4, –7, 16].
Write a program as a script file that doubles the elements
that are positive and are divisible by 3 or 5, and, raises to
the power of 3 the elements that are negative but greater
than –5.
133
Modify vector elements
• A vector is given by V = [5, 17, –3, 8, 0, –7, 12, 15,
20, –6, 6, 4, –7, 16]. Write a program as a script file
that doubles the elements that are positive and are
divisible by 3 or 5, and, raises to the power of 3 the
elements that are negative but greater than –5.
RELATIONAL AND LOGICAL
OPERATORS
• A relational operator compares two numbers by
determining whether a comparison statement (e.g.,
5 < 8) is true or false.
Note:-
1. No extension with file name means .mat file
2. If file name has extension other than (.mat) it will be treated
as ASCII data file
3. Load function is use only if data file contains numeric data
Reading and storing file data
>>edit abc.txt
Write following and save it
1 3 4 5 7
6 7 8 0 9
>>load abc.txt %it will load this file in workspace with a
% variable name abc, to check it write abc
>>abc
1 3 4 5 7
6 7 8 0 9
If we want to change the variable name write following
command
>>test=load (‘abc.txt’) %now data ‘abc.txt’ will store in variable ‘test’
Reading and storing file data
2.’save’ function: To save variables/data from workspace
to disk file
Different syntax are
save %save all workspace data in matlab.mat file
The problem, as entered, has no solution. Please check the input data.
fprintf command
With the fprintf command it is possible to start a new line in
the middle of the string. This is done by inserting \n before the
character that will start the new line.
Note:
1. '%6.2f %12.8f\n‘ here note the space b/w
to formats
2. \n means new line
3. ‘fprintf ‘ displays only real portion of complex
value
Low-level input-output functions
Subplots
Subplot(m,n,p) ≡ creates mxn subplots in the current figure (array of
subplots), m rows and n columns. p is the current subplot.
»subplot(2,2,1);
»plot(1:10)
»subplot(2,2,2)
»x = 0:.1:2*pi;
»plot(x,sin(x))
»subplot(2,2,3)
»x = 0:.1:2*pi;
»plot(x,exp(-x),’r’)
»subplot(2,2,4)
»plot(peaks)
»subplotex
3d plot in MATLAB Basic Graphics - 169
LOGLOG SEMILOGY
Both axes log Y
logarithmic linear X
SEMILOGX PLOTYY
log X 2 sets of
linear Y linear axes
»other_axes
3d plot in MATLAB Basic Graphics - 170
>> theta=0:0.1:10.*pi;
>> plot3(sin(theta),cos(theta),theta)
>> grid on
theta=0:0.1:10.*pi;
>> plot3(sin(theta),cos(theta),theta)
>> grid on
>> theta=0:0.1:10.*pi;
>> plot3(sin(theta),cos(theta),theta)
>> grid on
theta=0:0.1:10.*pi;
»plot_3d
>> plot3(sin(theta),cos(theta),theta)
>>Ref:
gridColor,
on Linestyle, Marker options
3d plot in MATLAB Basic Graphics - 171
>> turns=40.*pi;
>> theta=linspace(0,turns,4000); 1
Here is a piece of text!
>> x=cos(theta).*(turns-theta)./turns;
>> y=sin(theta).*(turns-theta)./turns;
0.5
>> z=theta./turns;
>> plot3(x,y,z)
0
>> grid on 1
>> turns=40.*pi;
>> >> text(0.5,0.5,0.75,'Here
theta=linspace(0,turns,4000); is a piece of 1
0
text!');
>> x=cos(theta).*(turns-theta)./turns;
>> y=sin(theta).*(turns-theta)./turns;
0
>> z=theta./turns; -1 -1
>> plot3(x,y,z)
>>»plot_3d
grid on
>>Ref: Color, Linestyle, Marker
text(0.5,0.5,0.75,'Here is a options
piece of
text!');
3d plot in MATLAB Basic Graphics - 172
»surf_3d
3d plot in MATLAB Basic Graphics - 173
x
σ = αe-βx[sin(θx)*cos(φy)]
»plot3d_soln
3d plot in MATLAB Basic Graphics - 175
»spec_plots
3d plot in MATLAB Basic Graphics - 176
3D Surface Plots
• Plot functions of the form: z=f(x, y)
• for each (x,y), we can compute a value for z
• this defines a surface in 3D space
• If we can define (x,y) at regular intervals, Matlab
provides powerful ways to plot the resulting function
as a mesh or surface in 3D.
x =-3 -2 -1 0 1 2 3
y =-3 -2 -1 0 1 2 3
z=f(x,y)
-5
xx =-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3
-3 -2 -1 0 1 2 3
-10
-3 -2 -1 0 1 2 3
2 -3 -2 -1 0 1 2 3
2 -3 -2 -1 0 1 2 3
0
0 -3 -2 -1 0 1 2 3
-2 -2
y-axis x-axis yy =-3 -3 -3 -3 -3 -3 -3
-2 -2 -2 -2 -2 -2 -2
NOTE: -1 -1 -1 -1 -1 -1 -1
0 0 0 0 0 0 0
xx varies along ROWS while yy varies
1 1 1 1 1 1 1
along COLUMNS 2 2 2 2 2 2 2
3 3 3 3 3 3 3
z=f(xx,yy) 177
3d plot in MATLAB meshgrid() Basic Graphics - 178
subplot(1,2,1);
mesh(X,Y,Z), title('Figure 26.5a: Opaque');
hidden on;
axis square off;
subplot(1,2,2);
mesh(X,Y,Z),title('Figure 26.5b:
Transparent');
hidden off;
axis square off;
3d plot in MATLAB mesh( ) Basic Graphics - 182
>> [x,y,z]=peaks(30);
>> mesh(x,y,z)
>> axis tight 5
>> xlabel('x-axis')
z-axis
0
>> ylabel('y-axis')
>> zlabel('z-axis')
-5
2
Suggestion: 2
0
0
Try using hidden off and -2 -2
hidden on to see what happens. y-axis x-axis
3d plot in MATLAB Basic Graphics - 183
>> xlabel('x-axis')
z-axis 0
>> ylabel('y-axis')
-5
>> zlabel('z-axis')
-10
Hint:: 2
2
0
If you just finished the previous 0
-2 -2
example, you need only type in y-axis x-axis
the new meshc( ) command.
meshz
3d plot in MATLAB Basic Graphics - 184
>> [x,y,z]=peaks(30);
>> meshz(x,y,z) 5
>> axis tight
>> xlabel('x-axis') 0
>> ylabel('y-axis')
>> zlabel('z-axis') -5
2
2
0
0
-2 -2
3d plot in MATLAB waterfall Basic Graphics - 185
>> [x,y,z]=peaks(30);
>> waterfall(x,y,z)
>> axis tight 5
>> xlabel('x-axis')
z-axis
>> ylabel('y-axis') 0
>> zlabel('z-axis')
-5
2
2
0
0
-2 -2
y-axis x-axis
3d plot in MATLAB Basic Graphics - 186
>> [x,y,z]=peaks(30);
5
>> surf(x,y,z) z-axis
>> axis tight 0
>> xlabel('x-axis')
>> ylabel('y-axis') -5
>> zlabel('z-axis') 2
2
0
0
-2 -2
y-axis x-axis
3d plot in MATLAB Basic Graphics - 188
>> [x,y,z]=peaks(30);
>> surf(x,y,z)
>> shading flat 5
>> axis tight
z-axis
>> xlabel('x-axis') 0
>> ylabel('y-axis')
>> zlabel('z-axis') -5
2
2
0
0
-2 -2
y-axis x-axis
3d plot in MATLAB Basic Graphics - 189
»defaults
Polynomials and Curve Fitting
Polynomials are functions that have the form:
m −1
y= p ( x)= am x + am −1 x
m
+ ..... + a1 x + a0
The coefficients am, am-1, …a0 are real numbers, and n,
which is a nonnegative integer, is the degree, or order,
of the polynomial.
In MATLAB, polynomials are represented by a row
vector in which the elements are the coefficients am,
am-1, …a0. The first element is the coefficient of the x
with the highest power. The vector has to include all
the coefficients, including the ones that are equal to 0.
191
Polynomials and Curve Fitting
192
Polynomials and Curve Fitting
Polynomials can be used to fit data points in two ways. In one the polynomial
passes through all the data points, and in the other the polynomial does not
necessarily pass through any of the points, but overall gives a good approximation
of the data.
Curve fitting with polynomials is done in MATLAB with the polyfit
function, which uses the least squares method. The basic form of the polyfit
function is: p = polyfit(x, y, n)
193
Polynomials and Curve Fitting
The value of a polynomial at a point x can be calculated with the function polyval
which has the form: polyval (p, x)
y = polyval(a, x)
compute the value of polynomial at value x
y = a(1) xn + a(2) xn-1 + … + a(n) x + a(n+1)
x can be a vector
194
polyfit, polyval
• p = polyfit( x, y, n);
– returns n'th order polynomial that's the closest fit
to x-y data (x and y are vectors, n a scalar)
• yp = polyval( p, x )
– returns the vector yp = the values of polynomial p
at each value in x
Linear Regression
•Assume n points, with each point having values
of both an independent variable x and a
dependent variable y.
1 n
=
y sample mean of the y values ∑
n k =0
yk
1 n 2
x2 =
sample mean-square of the x values ∑
n k =1
xk
1 n
xy =
sample mean of the product xy ∑
n k =1
xk yk
197
Best-Fitting Straight Line
a1 =
( xy ) − ( x )( y )
(x )−(x)
2 2
=
( x ) ( y ) − ( x )( xy )
2
(x )−(x)
a0 2
2
Alternately, a0= y − a1 x
=
y a1 x + a0
198
Find best fitting straight line equation
for the data shown below.
x 0 1 2 3 4 5 6 7 8 9
y 4.00 6.10 8.30 9.90 12.40 14.30 15.70 17.40 19.80 22.30
1 10 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 45
=
x ∑
10 k =1
x=
k
10
= = 4.50
10
199
1 10 2
x = ∑ xk
2
10 k =1
(0) 2 + (1) 2 + (2) 2 + (3) 2 + (4) 2 + (5) 2 + (6) 2 + (7) 2 + (8) 2 + (9) 2
=
10
285
= = 28.50
10
1 10
xy = ∑ xk yk
10 k =1
0 + 6.1 + 16.6 + 29.7 + 49.6 + 71.5 + 94.2 + 121.8 + 158.4 + 200.7
=
10
748.6
= = 74.86
10
200
(=
xy ) − ( x )( y ) 74.86 − (4.50)(13.02)
(x )−(x)
a1
2 2
28.50 − (4.50) 2
16.27
= =1.9721
8.250
a0 =y − a1 x =13.02 − 1.972 × 4.50 =4.1455
=y 1.9721x + 4.1455
201
•>> x = 0:9;
•>> yapp = 1.9721*x + 4.1455;
•>> y = [the 10 values of y];
•>> plot(x, yapp, x, y, 'o')
202
203
MATLAB General Polynomial Fit
The values of x are x1 , x2 , x3 ,...., xn .
The values of y are y1 , y2 , y3 ,...., yn .
The polynomial fit is to be of the form
y= p ( x)= am x m + am −1 x m −1 + ..... + a1 x + a0
•>> x = [x1 x2 x3.......xn];
•>> y = [y1 y2 y3......yn];
•>> p = polyfit(x, y, m)
•>> yapp = polyval(p, x)
•>> plot(x, yapp, x, y, 'o')
204
•>> x = 0:9;
•>> y = [the 10 values of y];
•>> p = polyfit(x, y, 1)
•p =
• 1.9721 4.1455
205
For data of previous two examples,
obtain a 2nd degree fit.
•Assume that the vectors x and y are still in
memory.
•>> p = polyfit(x, y, 2)
•p =
• 0.0011 1.9619 4.1591
•>> yapp2 = polyval(p, x);
•>> plot(x, yapp2, x, y, 'o')
• >> p1 = polyfit(t, y, 1)
• p1 =
• 0.8854 0.0000
• >> yapp1 = polyval(p1, t);
• >> plot(t, yapp1, t, y, 'o')
212
•(c) m = 3
•>> p3 = polyfit(t, y, 3)
•p3 =
• -2.8139 -0.0000 2.6568 0.0000
•>> yapp3 = polyval(p3, t);
•>> plot(t, yapp3, t, y, 'o')
213
214
• m=5
• >> p5 = polyfit(t, y, 5)
• p5 =
• 1.6982 0.0000 -4.7880 -0.0000 3.0990
0.0000
• >> yapp5 = polyval(p5, t);
• >> plot(t, yapp5, t, y, 'o')
215
216
For data below, obtain a 2nd degree fit
for the temperature T as a function of
the distance x.
x(ft) 0 1 2 3 4 5
T (deg F) 71 76 86 100 118 140
•>> x = 0:5;
•>> T = [71 76 86 100 118 140];
•>> p = polyfit(x,T,2)
•p =
• 2.0893 3.4107 70.8214
217
The equation is
T = 2.0893 x + 3.4107 x + 70.8214
2
•>> x1 = 0:0.1:5;
•>> T1 = polyval(p, x1);
•>> plot(x1, T1, x, T, 'o')
220
Fit for Problem 5-30a)
223
Symbolic Mathematics
Dr. Litan Kumar Saha
Assistant Professor
Department of Applied Mathematics
“Symbolic” toolbox allows you to:
Enter expressions in symbolic form with symbolic data
types.
Expand or simplify symbolic expressions.
Find symbolic roots, limits, minima, maxima, etc.
Differentiate and integrate symbolic functions.
Generate Taylor series of functions (among other tools).
Solve algebraic and differential equations symbolically.
Solve simultaneous equations (even some nonlinear).
Do variable precision arithmetic.
Create graphical representations of symbolic functions.
Creating Symbolic Variables
In order to use the symbolic toolbox, you
must create symbolic variables.
To create one symbolic variable, type:
x = sym('x');
syms x;
Creating Multiple Variables
To create several symbolic variables use
the syms command as follows:
syms K T P0;
P = P0*exp(K*T)
E = sym('m*c^2')
Symbolic equations
numerator=
2*(x + 3)^2
denominator=
(x^2 + 6*x + 9)
expand()
expand() is used to expand an expression
by expanding the products of factors in an
expression.
ans=
2*x^2 + 12*x + 18
factor()
The factor() command is used to factor an
expression into a product of terms.
ans=
(x + 3)^2
simplify()
The simplify() command uses the Maple
simplification algorithm to simplify each
part of an expression.
Enter the expression:
ans=
12*a - a^3 + 3*a^2 - 27
simple()
The simple() command executes many
techniques to simplify an expression; its
ans is the simplest expression.
simple(b)
ans =
3*a - (a + 3)*(a - 3)^2
b=
x^2 + 3*x + 2
E1=x^2 - 9
solve(E1)
ans=
3
-3
Hands on
ans =
1/2/a*( -b + (b^2 - 4*a*c)^(1/2))
1/2/a*( -b - (b^2 - 4*a*c)^(1/2))
ans =
-(b*x + c)/x^2
x= y= z=
-2 5 -6
Note that the solve function produces symbolic output. You can change the
output to numerical values with the double() command.
Substitution with subs()
The subs() command allows you to
substitute a symbol with another symbol or
assign a number to a variable.
syms a b c x y;
quadratic = a*x^2 + b*x + c;
yquadratic = subs(quadratic,x,y)
yquadratic =
a*y^2 + b*y + c
Multiple substitutions
You can use the subs() command to do
multiple substitutions in one command.
This is done by grouping the variables and
their substitutes (other variables or
numerical values) in braces.
subs(symbolic_function, {substitutant}, {substitute})
ans =
27
Plotting symbolical functions
Plotting symbolic functions in MATLAB is
done with the ezplot() set of commands.
The syntax of ezplot() when y is a function
of x is:
ezplot(y) x 2-2 x+3
50
y = sym('x^2 – 2*x + 3');
ezplot(y) 40
30
20
10
0
-6 -4 -2 0 2 4 6
x
Differentiation
MATLAB allows you to differentiate
symbolic functions with the diff() command.
The syntax of diff(), when f is a symbolic
function of the variable x and n is the order
of the derivative to be determined, is:
diff(f,'x' ,n)
diff(y,'x',1)
int(y,'x',a,b)
int(y,'x')
250
Solution of Differential Equations
with MATLAB
MATLAB has some powerful features for
solving differential equations of all types. We
will explore some of these features. The
approach here will be that of the Symbolic
Math Toolbox. The result will be the form of
the function and it may be readily plotted with
MATLAB.
251
ODE by Symbolic Math Toolbox
Symbolic Differential Equation Terms
2 n
dy d y d y
y 2 n
dt dt dt
y Dy D2y Dny
252
ODE by Symbolic Math Toolbox
Solve DE below with MATLAB.
dy
+ 2y =
12 y (0) = 10
dt
>> y = dsolve('Dy + 2*y = 12', 'y(0)=10')
y = 6+4*exp(-2*t)
254
ODE by Symbolic Math Toolbox
dy
+ 2y =
12sin 4t y (0) = 10
dt
d2y dy y '(0) = 10
2
20 y (0) = 0
+ 2 + 5y =
dt dt
d2y dy y (0) = 10 y '(0) = 0
2
+3 + 2y =
24
dt dt
255
ODE by Symbolic Math Toolbox
Solve DE below with MATLAB.
dy
+ 2y =
12sin 4t y (0) = 10
dt
>> y = dsolve('Dy + 2*y = 12*sin(4*t)',
'y(0)=10')
y = -12/5*cos(4*t)+6/5*sin(4*t)+62/5*exp(-2*t)
>> ezplot(y, [0 8])
>> axis([0 8 -3 10])
256
ODE by Symbolic Math Toolbox
257
Solve DE below with MATLAB.
2
d y dy
2
+ 2 + 5y =
20
dt dt
y (0) = 0 y '(0) = 10
>>ezplot(y, [0 5]}
258
259
Solve DE below with MATLAB.
2
d y dy
2
+ 3 + 2y = 24
dt dt
y (0) = 10 y '(0) = 0
>> y = dsolve('D2y + 3*Dy + 2*y = 24',
'y(0)=10', 'Dy(0)=0')
y =
12+2*exp(-2*t)-4*exp(-t)
262
Using ode Functions
The functions are generally called in the
same way; ode45 is used as an example:
[t, y] = ode45(odefun, tspan, y0)
y: solution array, where each column represents
one of the variables and each row corresponds to
a time in the t vector
odefun: function returning a column vector of
the right-hand-sides of the ODEs
tspan: time over which to solve the system
y0: vector of initial values
Solving ordinary differential equations
Ordinary differential equation can be solved
For first order ODE, simply prepare a function
y’ = f(x) and name it as yprime.m, then solve
by [t,y]=ode23(@yprime, tspan,y0)
Plot the graph to show the solution.
For higher order ODE, rewrite it into a system
of first order ODE and solve similarly.
264
Solving ordinary differential equations
To solve y’ - y – t = 0, y(0) = 0 the matlab
code yprime.m should be like,
function yp = yprime(y,t)
yp = y + t;
Solve it by
tspan=[0,10];
y0 = 0;
[t,y] = ode23(@yprime,tspan,y0)
2
+ ω sin θ =
2
0
dt
θ (0) = 1 θ '(0) = 0
268
Thank you!
271