Matlab_Tutorial12
Matlab_Tutorial12
Necmettin Yildirim
August, 2016
1
Contents
WHAT IS MATLAB?
• MATLAB is a high level language with many specialized functions and toolboxes to
ease simulation
• MATLAB stands for Matrix Laboratory
• Everything in MATLAB is encoded in a matrix
• This tutorial covers the basics of MATLAB, including matrices and functions, as
well as simulation of ordinary differential equations (ODEs)
• New College has a MATLAB server. You must login to the server to run MATLAB.
• You need a user account in order to be able to connect to the server.
• To connect to the server, use Windows Remote Desktop Connection(RDC). If you
have a Mac, you can download Microsoft Remote Desktop for free
• In Windows, you can access RDC using Start=>Accessories=>Remote Desktop
Connection. Both PC and Mac users should then type matlab and enter your NCF
email credential.
4
1.4. USING THE HELP BROWSER 5
• You can use MATLAB’s command window as a fancy calculator. In the command
window type the followings:
• MATLAB has thousands of built-in functions. You can search and get some help if
you know the name of a MATLAB function
Example 1. To get some help on MATLAB’s square root function "sqrt", just type
»help sqrt.
>>help sqrt
SQRT Square root.
SQRT(X) is the square root of the elements of X.
Complex results are produced if X is not positive.
See also sqrtm, realsqrt, hypot.
Reference page in Help browser doc sqrt
1.6. Vectors
>> x=[2, 3, 6]
x =
2 3 6
>> 2*x % you can multiply a vector by a constant
ans =
4 6 12
>> 5+x % you can add a constant to a vector
ans =
7 8 11
>> x=[2 3 6] % commas are optional
x =
2 3 6
>>x=linspace(X1, X2, N)
% generates a row vector of N linearly equally spaced points between X1 and X2.
1.8. Matrices
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
>> 5*eye(4)
ans =
5 0 0 0
0 5 0 0
0 0 5 0
0 0 0 5
>> ones(2,4) % create a 2x4 matrix with ones in every entry
ans =
1 1 1 1
1 1 1 1
>> zeros(2,4) % create a 2x4 matrix of zeros
ans =
0 0 0 0
0 0 0 0
>>
>> x=[2 4 6]
average = x*ones(3,1)/3
x =
2 4 6
average =
4
>>
Exercise 2. Try the same line as above with ones(1,3) replacing ones(3,1). What happens?
x=[0 1]
sin(x)
asin(x)
exp(x)
log(x) % ?? Log of zero? What’s that?
" #
1 2
Example 3. Apply sqrt to a simple 2 × 2 array of numbers such as .
2 4
1.10. Problems
35.7×64−73 37
(1) Compute 45+52
and 54 − 7 × 62 + 93 −652
2
(2) Evaluate a + abc + (a+0.5(ab−c))
√ if a = 15.62; b = −7.08; c = 62.5.
|ab|
(3) Use MATLAB’s linspace to create the following matrix,
0 4 8 12 16 20 24 28
A = 69 68 67 66 65 64 63 62
>> A = [1 2 3; 3 4 5; 6 7 8]
A =
1 2 3
3 4 5
6 7 8
>> A(2,3) % entry located in 2nd row and 3rd column of A
ans =
5
>> A(4,1)
??? Index exceeds matrix dimensions.
>> A(1:2,2:3) % extracts first two rows and 2nd and 3rd columns
ans =
2 3
4 5
>> A(:,2) % extracts 2nd column
ans =
2
4
7
>> A(3,:)% extracts 3nd row
ans =
6 7 8
>> A([1 3],[2 3]) % extracts 1st&3rd rows,2nd&3rd columns
ans =
2 3
7 8
>> K=[1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15; 16 17 18 19 20]
K =
11
2. OPERATIONS WITH MATRICES IN MATLAB 12
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
>> K(1:2:3,2:3:end) % extract 1st,3rd rows and 2nd&5th columns (until last)
ans =
2 5
12 15
x = B −1 t is the solution of the system of linear equation Bx = t, where x and t are column
vectors, and B is a matrix. Note the important differences between row vectors and column
vectors!
>> B
B =
-1 3 10
-9 5 25
0 14 2
>> t
t =
7
0
11
>> B
B =
-1 3 10
-9 5 25
0 14 2
>> s
s =
-1 8 5
>> y=s/B % solution of yB=s
2.2. RANDOMLY GENERATED MATRICES 14
x =
0.1686 0.0924 0.5023
Example 4. How can you generate 100 random numbers from the uniform distribution on
the interval [a, b]?
Answer: r = a + (b-a).*rand(100,1);
2.4. OUTPUT FORMATS 15
Example 5. How can you generate a 6x6 random matrix from the uniform distribution on
the interval [15, 25]?
Answer: 15+round(10*rand(6))
>> A= 15+round(10*rand(6))
A =
24 22 24 15 20 16
24 20 23 20 16 23
18 20 21 17 22 23
22 24 17 25 15 22
17 21 17 22 16 16
15 21 24 20 20 22
>> round(-1.8)
ans =
-2
>> ceil(-1.8)
ans =
-1
>> floor(-1.8)
ans =
-2
>> pi
ans =
3.1416
>> format long
>> pi
ans =
3.141592653589793
2.4. OUTPUT FORMATS 16
+ : addition
- : subtraction
* : multiplication
^ : power
’ : transpose
\ : left division
/ : right division
.* : term by term multiplication
.^ : term by term power
.\ : term by term left division
./ : right division
>> max(A)
ans =
0.4897 0.9203 0.9427 0.9831
Exercise 7. Use MATLAB to check if the columns of V are eigenvectors and the diagonal
entries of D are corresponding eigenvalues of U
>> A*V(:,1)-D(1,1)*V(:,1)
ans =
1.0e-014 *
0.1332 -0.0444 -0.0222
You can concatenate matrices and arrays in MATLAB. See the examples below.
Let a, b, A and B be the following matrices
>> a=rand(2,2)
a =
0.8407 0.8143
0.2543 0.2435
>> b=rand(3,2)
b =
0.9293 0.2511
0.3500 0.6160
0.1966 0.4733
2.9. CONCATENATION OF MATRICES AND ARRAYS IN MATLAB 20
Z(:,:,1) =
1 2 3 4 5
6 7 8 9 10
Z(:,:,2) =
3 6 9 12 15
18 21 24 27 30
A =
1 3
6 8
>> A(1,:)=[ ]% Eliminate the first row
A =
6 8
2.10. Problems
2 9 0 0 −1
0 4 1 4 6 h i
(1) Define A = , b = and a = 3 −2 4 −5 and calculate
7 5 5 1 0
7 8 7 4 9
the following matrices(when defined)
(a) A · b
(b) a + 4
(c) b · a
(d) a · bT
(e) A · aT
(2) Explain any difference between the answers that MATLAB returns when you type
in A*A, A^2 and A.^2
(3) What is the command that isolates the submatrix that consists of the 2nd to 3rd
rows of the matrix A?
(4) Consider
0 4 8 12 16 20 24 28
A = 69 68 67 66 65 64 63 62
10 100 500 1000 2000 4000 8000]. Then, create a new vector y in which each entry
of the vector is calculated by y = 1 + n1 n from each n. Compare the elements
>>f=@(x) x^2+1
f =
@(x)x^2+1
>> f(2)
ans =
5
>>f=@(x,y) x^2+y/5
f =
@(x,y)x^2+y/5
>>f(1,5)
ans =
2
>>f=@(x,y,z) 1/z+x^2+y/5;
>>f(1,2,5)
ans =
1.6000
24
3.3. PLOT FUNCTIONS 25
>>f=@(x) x(1)*x(2)+x(1);
>>f([3 4])
ans =
15
>>f=@(x) x(1)+x(2)/7+x(3)^4;
>>f([1 1 1])
ans =
2.1429
• If you type
>>save myfile
in the command window, all defined variables will be saved to a file called myfile.mat
in the current directory. This file format is specific to MATLAB. You can also select
a subset of variables to be saved by typing their names after the file name such as
>>save myfile a,b,C
• If you later enter load myfile, the saved variables are returned to the workspace,
overwriting any presently defined values assigned to the same names.
Plotting with ezplot. ezplot makes two-dimensional (2D) plots of explicit, implicit
or parametric functions.
ezplot for explicit functions. ezplot(fun) plots the function fun(x) over the default
domain −2π < x < 2π, where y=fun(x) is an explicitly defined function of x.
>> ezplot(@sin)
sin
0.5
−0.5
−1
−6 −4 −2 0 2 4 6
x
ezplot(@sin,[0 10*pi])
sin
0.5
−0.5
−1
0 5 10 15 20 25 30
x
ezplot for implicit functions. ezplot(fun) plots the implicitly defined function fun(x,y)
= 0 over the default domain −2π < x < 2π and −2π < y < 2π.
x4+y4−225 = 0
6
0
y
−2
−4
−6
−6 −4 −2 0 2 4 6
x
3.4. PLOT MULTIPLE CURVES IN 2D WITH PLOT: VECTOR VS MATRIX 27
ezplot(fx,fy,[tmin ,tmax]) plots f x(t) and f y(t) over tmin < t <
tmax .
>> x= @(t) exp(-t).*cos(8*t);
>> y= @(t) exp(-t).*sin(8*t);
>> ezplot(x,y,[0 3])
x = exp(−t) cos(8 t), y = exp(−t) sin(8 t)
0.8
0.6
0.4
0.2
y
−0.2
−0.4
3.3.1. Plot curves in 2D with “plot” function. plot(X,Y) plots vector Y versus
vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the
matrix, whichever line up.
>> x = -2*pi:(pi/10):2*pi;
>> y1 =sin(x);
>> y2 =cos(x);
>> plot(x,y1,x,y2)
1
0.8
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−8 −6 −4 −2 0 2 4 6 8
Example 8. X and Y are both matrices, then they must have equal size. plot(X,Y) plots
columns of Y versus columns of X. If Xis a vector , then the plot function plots each matrix
column Y versus X.
>> x=[0:.1:1];
>> A=[1:11;10:-1:0]
3.5. PLOTTING CURVES IN 3D WITH PLOT3 28
>> plot(x,A)
12
10
0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
• plot3(x,y,z), where x, y and z are three vectors of the same length, plots a line in
3-space through the points whose coordinates are the elements of x, y and z.
>> t = 0:pi/50:10*pi;
>> plot3(sin(t),cos(t),t); %parametric functions
40
30
20
t
10
0
1
0.5 1
0 0.5
0
−0.5 −0.5
−1 −1
cos(t) sin(t)
>> x=[0:.1:5];
>> y=2*[0:.1:5];
>> f=@(x,y) sin(x).^2+cos(y).^2; % explicit functions
>> plot3(x,y,f(x,y))
1.5
f(x,y)
0.5
0
10
5
4
5 3
2
1
0 0
y x
3.7. PLOTTING IN 3D WITH SURF 29
plot3(X,Y,Z), where X1, Y1, Z1 are vectors or matrices, plots one or more lines in three-
dimensional space through the points whose coordinates are the elements of X, Y, and Z.
>> x1=0:4;
>> x2=0:5;
>> [x,y]=meshgrid(x1,x2) % creating a meshgrid
>> [x,y]=meshgrid(-1:.1:1,-3:.02:2);
>> z=sin(x.*y).*cos(y);
>> plot3(x,y,z)
0.5
z=f(x,y)
−0.5
−1
2
1
0
0.5
−2 0
−0.5
−4 −1
y x
0.5
−0.5
−1
2
1 1
0 0.5
−1 0
−2 −0.5
−3 −1
>> [x,y]=meshgrid(-1:.1:1,-3:.02:2);
>> z=sin(x.*y).*cos(y);
>> surfc(x,y,z)
0.5
−0.5
−1
2
1 1
0 0.5
−1 0
−2 −0.5
−3 −1
3.9. image
The image command is useful for large matrices which would take too much computing time
to plot
>> A=[1,2;3,4];
>> imagesc(A),colorbar
3.10. PROBLEMS 31
0.5 4
3.5
1.5 2.5
1.5
2.5 1
0.5 1 1.5 2 2.5
3.10. Problems
1
(1) Compute 2 + 3, 2 × 3,2/3, 23 , 2 3 , log(3), cos(3), sin(5) in the command line.
(2) Plot f (x) = e−x on [−2, 2].
(3) Plot g(t) = |t| on [−1, 1].
(4) Use linspace to generate a row vector of 100 linearly evenly spaced points between
-1 and 1 and evaluate f (x) = x2 at each point. Plot the graph.
(5) Make surface plots of the following functions over the given ranges:
(a) (x2 + 3y 2 )e−x −y , −3 ≤ x ≤ 3, −3 ≤ y ≤ 3.
2 2
An M-file is a plain text file containing MATLAB commands and saved with the file name
extension .m. There are two types:
• Scripts
• Functions
Driver Code (MATLAB Script): sends inputs to the function and gets back output
Function Code (MATLAB function): takes in inputs from driver and runs an
algorithm and sends back outputs to the driver
32
4.1. DRIVER CODES AND FUNCTIONS IN MATLAB 33
Reminder : an extremely important type of statement in any M-file is the comment, which
is indicated by a percent sign %. Any text on the same line after a percent sign is ignored.
Furthermore, the first block of comments in an M-file serves as documentation for the file
and will be typed out in the command window if the help command is used on the file.
Body of Algorithm
Output
Example 11. Open a new MATLAB editor page and type the following MATLAB commands
and save it under a name Driver.m. Then go to the command window type Driver and push
ENTER. What happens?
function Output=FunctionName(Input)
Body of Algorithm
Output=...;
ax2 + bx + c = 0
−b ± d
x1,2 =
2a
√
d = b2 − 4ac
% Driver
a=1;
b=4;
c=3;
[x1,x2] = quadform(a,b,c)
In a separate file:
These statements are executed or not depending on whether a relation holds true.
MATLAB’S RELATIONAL AND LOGICAL OPERATORS 35
if (relation)
statement(s)
elseif (relation)
statement(s)
elseif (relation)
statement(s)
.
.
.
else
statement(s)
end
if (relation)
statement(s)
end
if (5>3)
disp(’5 is bigger than 3’)
end
Example 16. MATLAB function with an if..else..if statement that computes log3 (x) for
a given number x > 0
MATLAB’S RELATIONAL AND LOGICAL OPERATORS 36
function a=log3(x)
% This code computes the base 3 logarithm of x
a = NaN;
if sum(-x>0)==0
a=log(x)/log(3);
else
disp(’x has negative value(s)’)
end
Example 17. The Newton-Raphson method (also known as Newton’s Method) for finding
roots of the equation f (x) = 0 is
f (xn )
xn+1 = xn −
f 0 (xn )
To run this method, an initial guess x0 has to be provided. Now, write a MATLAB function
√
that implements this method to approximate 5 in 4 steps
xn 5
xn+1 = +
2 2xn
Given x0 , we want to compute x4 .
function y = AbsVal(x)
y=x;
if x<0
y=-x;
end
for j=first:last
(statements)
end
Example 19. The following script prints the first four positive integers
for i=1:4
i
end
Example 20. The following script squares each entry in a given vector v with length 10
Example 21. The Newton-Raphson method for the same function f (x) = x2 − 5 with a
for..end loop in 4-steps is given below
4.4. STRUCTURE OF for...end LOOP 38
% Driver part
x0=1;
RootOut=NewtonAlg(x0)
% function part
function [x_out]=NewtonAlg(x_in)
for i=1:4
x_out = x_in/2+5/(2*x_in) ;
x_in = x_out;
end
for j=j0:jn
(statements)
for k=k0:kn
(statements)
end
end
for i=1:2
for j=1:3
[i,j]
end
end
i = 1 1 1 2 2 2
j = 1 2 3 1 2 3
Example 23. A function to compute the transpose of a given nxn square matrix A
function B=transposeA(A)
%This code computes transpose of a matrix
[m,n] = size(A);
for i=1:n
for j=1:n
B(i,j)=A(j,i);
4.4. STRUCTURE OF for...end LOOP 39
end
end
Example 24. Write a function that adds up all the entries in a given mxn matrix A
function [s_sum]=Sum_of_A(A)
% This function computes sum of all entries in a matrix
[m,n] = size(A);
s_sum=0
for i=1:m
for j=1:n
s_sum=s_sum+A(i,j);
end
end
Example 25. A function that produces an upper triangular mxn matrix B from an mxn
matrix A. In other words,
a11 a12 a13 ... a1n a11 a12 a13 ... a1n
a21 a22 a23 ... a2n 0 a22 a23 ... a2n
A= a31 a32 a33 ... a3n ⇒B= 0 0 a33 ... a3n
.. .. .. .. .. .. .. .. .. ..
. . . . . . . . . .
am1 am2 am3 ... amn 0 0 0 ... amn
Answer:
function [B]=Upper(A)
[m,n]=size(A);
B=zeros(m,n);
for i=1:m
for j=i:n
B(i,j)=A(i,j);
end
end
h i
Example 26. The dot product of two vectors with same sizes v = v1 v2 ... vn and
h i
w = w1 w2 ... wn are defined as
4.5. STRUCTURE OF while...end LOOP 40
n
X
vw = vi wi = v1 w1 + v2 w2 + ... + vn wn
i=1
i=1
Exercise. Write a function that takes in v and w and sends out their dot product and
l2 −norms.
while (expression)
(statement)
end
Example 27. The following code prints the first four positive integers and employs a
while...end loop
j=1;
while j<=4
j
j=j+1;
end
Example 28. The following code computes roots of x2 − 5 = 0 , until numerical error
becomes less than given a preset error toleranceEr and uses while...end
% Driver part
clc
Er = 1e-8;
x_out = 0;
x_in = 1;
[x_out] = NewtonAlg(x_in,Er)
% function part
function [x_out]=NewtonAlg(x_in,Er)
while abs(x_in-sqrt(5))>Er
4.5. STRUCTURE OF while...end LOOP 41
x_out = x_in/2+5/(2*x_in) ;
x_in = x_out;
end
Example 29. Determine what the following MATLAB function does. Then explain the
output of [a] = exple(10)
Example 31. Generate 2000 random numbers between 0 and 2000 and count how many of
them are in the following intervals. Then use MATLAB’s bar built-in function to plot the
counts you computed to produce a histogram.
• (a) [0.00,0.25)
• (b) [0.25,0.50)
• (c) [0.50,0.75)
• (d) [0.75,1.00]
Answer:
A = rand(1,2000);
count = zeros(1,4);
for i = 1:2000
if (A(i)>=0.0 && A(i)<0.25)
count(1)=count(1)+1;
elseif (A(i)>=0.25 && A(i)<0.50)
4.5. STRUCTURE OF while...end LOOP 42
count(2)=count(2)+1;
elseif (A(i)>=0.50 && A(i)<0.75)
count(3)=count(3)+1;
else
count(4)=count(4)+1;
end
end
√
Example 32. Write a function that approximates 5 using Newton’s Method in n steps in
two different ways:
Example 33. Write a MATLAB script with a for..end loop and if..else..end statements
that plots the graph of the following piecewise function
x 2 if − 1 ≤ x < 0.5
f (x) =
0.25 if 0.5 ≤ x ≤ 1
Answer:....
4.5. STRUCTURE OF while...end LOOP 43
x=[-1:.1:1];
for i=1:length(x)
if x(i)<0.5
f(i)=x(i)^2;
else
f(i)=0.25;
end
end
plot(x,f)
xlabel(’x’)
ylabel(’f’)
Example 34. Develop a MATLAB function that solves the linear system Ax = b for a given
nxn square matrix A and a nx1 vector b (Use if...end statements to check if the system has
a solution first)
4.6. PROBLEMS 44
4.6. Problems
(4) Develop a driver called Driver_Quad.m and two other MatLab functions called
R_Quad.m and Disc_Quad.m that solves a quadratic equation
ax2 + bx + c = 0
Organize your codes so that the driver code Driver_Quad.m supplies the coefficients
a, b and c into the function file R_Quad.m, that computes the roots x1 and x2 from
the quadratic formula and sends them back to the driver Driver_Quad.m. While
computing the roots in R_Quad.m, have it call another function file Disc_Quad.m
to get the discriminant value calculated.
(5) Plot the graphs of f (x) = x2 , g(x) = x3 for x = −1, . . . , 1 on the same axis. Label
the x and y axes and create a legend indicating which graph is which.
(6) Let x = [ 3, 2, −1, 5, 8 ], determine outputs of each of the following MATLAB
command
(a) x(end)
(b) x(3)
(c) length(x)
(d) x(2:4)
(7) A magic square is an n×n matrix in which each integer 1, 2, . . . , n2 appears once
and for which all the row, column, and diagonal sums are identical. MatLab has a
command magic that returns magic squares. Check its output when n=5 and n=20
and use MatLab to verify the summation property. (The antidiagonal sum will be
the trickiest. Look for help on “fliplr” .)
(8) Let P1, P2, and P3 be the vertices of an equilateral triangle. Start with a point
anywhere inside the triangle. At random, pick one of the three vertices and move
halfway toward it. Repeat indefinitely. If you plot all the points obtained, a very
clear pattern will emerge. (Hint: This is particularly easy to do if you use complex
numbers. If z is complex, then plot(z) is equivalent to plot(real(z),imag(z)).)
4.6. PROBLEMS 45
(9) Generate 100 random matrices using randn(100), and plot all of their eigenvalues
as dots in the complex plane on one graph. (Thus, you should see 10,000 dots.)
Use axis equal to make the aspect ratio one-to-one. You should see a fairly striking
result.
CHAPTER 5
roots([1 3 2])
ans=
-2
-1
>> S=roots([1 1 1 1 1 1 ])
S =
0.5000 + 0.8660i
0.5000 - 0.8660i
-1.0000
-0.5000 + 0.8660i
-0.5000 - 0.8660i
-1.5000 + 1.6583i
-1.5000 - 1.6583i
>> real(S)
ans =
-1.5000 -1.5000
>> imag(S)
ans =
1.6583 -1.6583
2x5 − 13x2 + 5x + 1 = 0
f (x) = sin x
clear all
clc
clf
%% List of functions
fcn=@(x) sin(x);
[xout fval] =fminbnd(fcn,-5*0,1)
plot(xout,fval,’ro’,’markersize’,20),
hold on
u=[-3:.01:3];
plot(u,fcn(u))
Exercise 42. Use the code above to minimize the following functions
Example 43. Minimize the following function (called the Rosenbrock Valley Function) start-
ing from x0 = (2, 3)
f (x1 , x2 ) = 100(x2 − x1 )2 + (1 − x1 )
%% Rosenbrock Valley
f =@(x) 100*(x(2)-x(1)^2).^2+(1-x(1)).^2;
[xout fval] =fminsearch(f,[2 2])
%% Plotting Rosenbrock Valley
[X,Y]=meshgrid(-3:0.2:3,-3:0.2:3);
surfc(X,Y,f(X,Y))
Example 44. Minimize the following function (Rasting Function) starting from (2, 3)
%% Rastrigin function
[xout fval] =fminsearch(f,[2 2])
f =@(x) 20+10*cos(2*pi*x(1))+10*cos(2*pi*x(2));
%% Plotting Rastrigin function
[X,Y]=meshgrid(-2:0.02:2,-2:0.02:2);
Z = 20 +10*cos(2*pi*X)++10*cos(2*pi*Y);
surfc(X,Y,Z)
Example 45. (Data fitting)Codes that mimimize the sum of square differences between the
data and a given function
b = 1;
c = 1;
xdata = -5:.5:5;
per = 30/100;
ydata = fcn(xdata,a,b,c).*(1+per*randn(1,length(xdata)));
%% Estimate a,b,c
a0 = rand;
b0 = rand;
c0 = rand;
x0 = [a0 b0 c0];
[xout fval] = fminsearch(@sum_square,x0,[],xdata,ydata)
%% ------------ Objective function -------
function SSE= sum_square(p,xdata,ydata)
a = p(1);
b = p(2);
c = p(3);
%% Definition of the objective function
M = fcn(xdata,a,b,c);
SSE = sum((ydata-M).^2);
% Plot every step plot(xdata,ydata,’ro’,xdata,M,’b-s’),
axis([2*min(xdata) 2*max(xdata) 4*min(ydata)-2 2*max(ydata)])
pause(.01)
%% ------------ Model --------------------
function fout = fcn(xdata,a,b,c)
fout = a*sin(b*xdata)+c;
5.6. MATLAB: USING THE DEBUGGER 51
X = lsqcurvefit(FUN,X0,XDATA,YDATA)
starts at X0 and finds
coefficients X to best fit
the nonlinear functions
Example 46. Following code minimize the difference between data and the function
f = a cos(bx) + c
% Driver
clc
% Input data set
xdata=[-5.0 -4.0 -3.0 -2.0 -1.0 0.0 1.0 2.0 3.0 4.0 5.0];
ydata =[8.5 10.8 11.9 11.5 9.7 7.0 4.3 2.4 2.0 3.2 5.5];
% Initial estimate
X0=2+rand(1,3);
% Upper and lower bounds
LB=[];
UB=[];
% call lsqcurvefit
[xout,resnorm] = lsqcurvefit(@fcn,X0,xdata,ydata,LB,UB,[],ydata)
% the optimization function
function f=fcn(X0,xdata,ydata)
a=X0(1);
b=X0(2);
c=X0(3);
f=a*cos(b*xdata)+c;
% plotting for every estimnate
plot(xdata,ydata,’ro’,xdata,f,’b’)
pause(.01)
The debugger helps us understand what a program actually does (rather than what we want
it to do)
5.7. MATLAB HINTS (SOURCE: TOBIN A. DRISCOLL 2009) 52
• Setup breakpoints in an m-file by pressing F12, clicking on the file icon with the red
dot, or clicking on the "-" in the margin of the editor.
• Execute the m-file at the command line and note the prompt change to K>>.
• dbstep executes the next command in the program (after the breakpoint or previous
command)
• dbcont executes all remaining steps of the program until the next breakpoint or
termination of the program.
• dbquit exits debugging mode
A few things things about MATLAB that can come in handy, but which often do not come
to the attention of beginners:
• Use the up-arrow key to cycle through previous commands. If you type specific
characters first, only commands matching the typed characters will be recalled.
• If a computation is taking too long, interrupt it by pressing Ctrl-C (after making
sure the Command Window is active in the operating system).
• Even when MATLAB displays only 4–5 digits of a result, it’s storing about 15
significant digits. (You can see them all by typing format long). By copying or
retyping a displayed result, you throw away a lot of information. Wait until the end
of the calculation to round off your results.
• MATLAB has great debugging tools. Run your code step by step to uncover errors.
Run someone else’s code step by step to understand it thoroughly.
• The code checker (checkcode) makes some good suggestions
• The previous two items alone are sufficient reasons to use the built-in MATLAB
Editor for writing code. Open it by entering edit.
• If the execution of your code is too slow to suit, use the Profiler to find the slowest
steps.
• Don’t use a screen or window capture function to paste figures into a document
or presentation. The results look cheesy and amateurish, MATLAB’s use print
command (look at the help file to get more about usage of this command)
• After you have properly exported a figure to a graphics file, save that figure again
in the native FIG format. You may want to make changes to it someday.
5.8. PROBLEMS 53
5.8. Problems
Explain what each of the following MATLAB codes does when it is run. Write next to each
line what that line does
%% ===================================================’)
%% Code 1
%% ===================================================’)
clear all
clc
clf
A = rand(1,1000);
C = zeros(1,5);
for I = 1:length(A)
if A(i)<=.2
C(1) = C(1)+1;
end
if A(i)>.2 & A(i)<=.4
C(2) = C(2)+1;
end
if A(i)>.4 & A(i)<=.6
C(3) = C(3)+1;
end
if A(i)>.6 & A(i)<=.8
C(4) = C(4)+1;
end
if A(i)>.8 & A(i)<=1
C(5) = C(5)+1;
end
end
xx = [1:5];
plot(xx,C)
%% ===================================================’)
%% Code 2
%% ===================================================’)
clear all
clc
clf
5.8. PROBLEMS 54
A = rand(1,100);
L = 1;
for j=1:length(A)/10
K(L,1:10) = A(10*(j-1)+1:10*j);
L = L+1;
end
%% ===================================================’)
%% Code 3
%% ===================================================’)
clear all
clc
clf
A = pi*100*ones(1,5);
sprintf(’ %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n’, A)
sprintf(’|%e|%15e|%f|%15f|’, pi*50*ones(1,4))
%% ===================================================’)
%% Code 4
%% ===================================================’)
clear all
clc
clf
R = 2.9;
t = [0:.1:1];
Rx = [R*t.*(1-t)];
subplot(2,1,1),plot(t,t,’b’), hold on;
subplot(2,1,1),plot(t,Rx ,’r’), hold on;
N = length(t);
x(1) = 0.6;
for i=1:length(t)
x(i+1) = R*x(i)*(1-x(i));%
end
plot(t,x)
%% ===================================================’)
%% Code 5
%% ===================================================’)
clear all
5.8. PROBLEMS 55
clf
clc
%% ====================== Part(A) ===================
R = 2.9;
t = [0:.1:1];
N = length(t);
x(1)= 0.6;
for i=1:length(t)
x(i+1) = R*x(i)*(1-x(i));%
end
subplot(2,1,1),plot(t,t,’b’), hold on;
subplot(2,1,1),plot(t,R*t.*(1-t),’r’), hold on;
axis(’square’);
axis([0 1 0 1]);
set(gca,’XTick’,(0:.1:1),’YTick’,(0:.1:1))
grid on;
xlabel(’xt’)
ylabel(’xt+1’)
%% ====================== Part(B) ===================
subplot(2,1,1),line([x(1) x(1)],[0 x(2)],’Color’,’g’)
subplot(2,1,1),plot(x(1), x(1),’ko’);
for ic=1:length(t)-2
subplot(2,1,1), line([x(ic) x(ic+1)],[x(ic+1) x(ic+1)],’Color’,’g’)
subplot(2,1,1), line([x(ic+1) x(ic+1)],[x(ic+1) x(ic+2)],’Color’,’g’)
subplot(2,1,1), plot(x(ic+1), x(ic+1),’ko’);
pause
end
line([x(N) x(N+1)],[x(N+1) x(N+1)],’Color’,’g’)
A MATLAB code for solving a differential equation with an initial condition (IVP) usually
consists of two parts: (1) driver part and (2) differential equation part. The driver part
constitutes initial values for dependent variables, parameter values, one of MATLAB’s dif-
ferential equation solver and a common for plotting the solution, whereas the function part
consists of the differential equation. The general form of an initial value problem (IVP) is
dx
= f (t, x)
dt
x(t0 ) = x0
To solve this problem with the right hand side of the differential equation f = f (t, x), the
initial starting point (t0 , x0 ) and a range [t0 , tend ] for the independent variable t have to be
provided. There are a number of ODE solvers in MATLAB, each using a different numerical
method. Here, our focus is on the solver ode15s.
This is the simplest way of solving an ODE with an initial condition is to use inline function.
Consider the following example
Example 47. Numerically approximate the solution of the first order differential equation
given below
dx
= 0.5x, and x(0) = 1.0
dt
on the interval x ∈ [0, 5]. We begin by defining the function f (t, x) in dx
dt
= f (t, x):
fcn=@(t,x) -.5*x;
[Tout,Xout]=ode15s(f,[0 .5],1);
plot(Tout,Xout)
xlabel(’t’)
ylabel(’x(t)’)
and MATLAB returns two column vectors, the first with values of Tout and the second with
values of Xout(solution). Since the MATLAB output is long and it is omitted here. Now we
can plot the results
plot(Tout,Xout)
xlabel(’t’)
ylabel(’x(t)’)
dx
= k1 ln(x) + x − 1
dt
x(0) = 0.8
if k1 = −0.4.
MATLAB code for this problem is given below.
Below is a template you can modify to develop your code to solve a system of differential
equation involving a number of parameters:
6.3. SOLVING A SYSTEM ODES 59
dx! x1 x2
= ax1 (1 − x1 ) −
dt k + x1
dx2 x1 x2
= b − x2
dt k + x1
x1 (0) = 1 and x2 (0) = 1
The MATLAB script and function solving this system of differential equations are given
below. The figure is shown below the code.
2
x1(t) and x2(t)
1.5
0.5
0
0 10 20 30 40 50 60 70 80 90 100
time