Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Final MATLAB (1) (1) - 1

MATLAB is an interactive software used for engineering and scientific applications. It performs most functions of a computer language without requiring in-depth programming knowledge. MATLAB allows for plotting, complex number handling, and matrix operations. Key features include the command window for interacting with MATLAB, built-in mathematical functions, array construction and indexing, and vector and matrix operations.

Uploaded by

soham kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Final MATLAB (1) (1) - 1

MATLAB is an interactive software used for engineering and scientific applications. It performs most functions of a computer language without requiring in-depth programming knowledge. MATLAB allows for plotting, complex number handling, and matrix operations. Key features include the command window for interacting with MATLAB, built-in mathematical functions, array construction and indexing, and vector and matrix operations.

Uploaded by

soham kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

INTRODUCTORY MATLAB

ABOUT MATLAB Example: S= 1+2, fun = sin (pi/4)

 Interactive Software used in various >> S=1+2;


areas of engineering and scientific
applications. >>fun = sin(pi/4)
 Not a computer language though it fun =
does most of the work of a computer
language. 0.7071
 Easy to learn.
 Does not require the in depth
knowledge of computer programming Try yourself:
like compiling and linking. (Can be
looked upon as an advantage and also 2 + floor(6 / 9 + 3 * 2) / 2 - 3
as a disadvantage).
 Plotting. COMMENTS, PUNCTUATION AND ABORTING
 Interactive mode may reduce EXECUTION
computational speed.
 Semicolon at the end of a command
COMMAND WINDOW suppresses the printing of computed
results.
 When we run MATLAB by double
clicking on MATLAB on the desktop, it  All text after a percent sign (%) is taken
creates one or more windows on the as a comment statement.
computer monitor. Out of these,
COMMAND WINDOW is the place Multiple commands can be placed on one line if
where we interact with MATLAB. they are separated by commas or semicolons.

 The prompt >> is displayed in the  Commas tell MATLAB to display results;
command window and when the semicolonssuppress printing.
command window is active, a blinking
 To continue expressions or commands
cursor should appear on the right side
onto additional lines, we use … in
of the prompt.
succession. Comment lines and variable
 Simple Computations can be performed names cannot be split between two
by typing the command and pressing lines.
enter.
 MATLAB processing can be interrupted
at any moment by pressing Ctrl+C.
COMPLEX NUMBERS Note: Can handle specialized mathematical
functions Bessel, Legendre, Beta function
 No special handling for complex etc.
numbers.
NUMBER DISPLAY FORMATS

By default,
% Complex numbers
 if a result is an integer, it is displayed as
c1=1-2i % the appended i signifies
an integer.
the imaginary part

c1= 1-2j % also works  if real number, four digits to right of


c1= 1-2*(sqrt(-1)) % also works decimal place is displayed.
realpart_c1=real(c1) % gives real
part  candisplay
change thisformats:
default behaviour.
imagpart_c1=imag(c1) % gives % Number
imaginary part
mag_c1=abs(c1) % gives magnitude of  Can change this default behaviour .
formatshort;
c1 pi = 3.14159
angle_c1= angle(c1) % gives angle in formatlong;
radians pi = 3.141592653589793
formatshorte;
pi = 3.14159e+000
z=3+i*3;
formatlonge;
compass(z) % polar representation pi = 3.141592653589793e+000
abs(z) % Modulus of complex number
angle(z) %argument of complex number

SIMPLE ARRAY
% Mathematical functions
x=sqrt(2) %gives square root of 2
y=rem(23,4) % remainder function,  Start with a left bracket, enter the
23/4 has remainder 3 desired values separated by spaces (or
commas) and then close it using a right
y_deg=30; %degree to be converted to
radians
bracket.
y_rad=y_deg*pi/180;
y1=sin(y_rad)  Colon notation

x1=exp(2) %exponential function e^2 x=first:last

x=first:increment:last
Try yourself:
 linspace command
(2+6*i)/(9*i)*(1+i)
x=linspace (first, last, n)
MATHEMATICAL FUNCTIONS
Note: These arrays have one row and multiple
 sqrt, sin, cos, sinh, asin, acos, exp, log
columns.
etc.
a) assign the first row of A to a vector
% ARRAY CONSTRUCTION called x1
b) assign the last 2 rows of A to an
% Method 1. array called y
x=[0, 0.1*pi,0.2*pi,0.3*pi, c) compute the sum over the
0.4*pi,0.5*pi,0.6*pi,0.7*pi,0.8*p columns of A
i,0.9*pi,pi]
y=sin(x)
COLUMN VECTORS
% ARRAY INDEXING
 Specify it element by element and
x(3) % gives 3rd element of the
array separate values with semicolons.

x(1:5) % access elements from 1 Note: Separating elements by spaces or


to 5 commas specifies elements in different
columns, whereas separating elements by
x(7:end) %starts with 7th and
continues till last element semicolons specifies elements in different rows.

y(3:-1:1) %start with third  b=a’ transposes.


element, count down by 1, stop at  length(a) gives length of the vector ‘a’.
1
% gives third, second and first  a.*a is for component wise application
element of the operator a on a; if
a=[1 2 3];
x(2:2:7) % start with second
a.*a=[1 4 9]
element, count up by 2, stop when
you get 7  a.^m gives mth power of components
%Method 2 of a.
 a./b gives component wise division of
x1=3:20 % takes values from 3 to
20 incrementing 1 elements of a by elements in b.
 a *b gives dot product of the vectors a
%Method 3 and b.
x= (0:0.1:1)*pi % 0 to pi in  cross(a,b) gives cross product of 2
increments of 0.1*pi three dimensional vectors.
 unique(a) gives the same values as in
% Method 4
echoon
array a but without repetitions.
x=linspace(0,pi,11) ;  sort(a) sorts a in ascending order, for
y=sin(x) matrices sorts columns in ascending
%linspace(first_value,last_value,
number of values) order.
echooff  setdiff(a,b) returns vector of values in
Try yourself: a but not in b.
 max(a);min(a) gives maximum and
Given the array A = [ 2 4 1 ; 6 7 2 ; 3 5 9], minimum component of vector ‘a’.
provide the commands needed to
 mean(a);std(a) gives mean and
standard deviation of components.
% Vector operations Example: A=[1 2 3 4; 5 6 7 8; 1 1 2 3] denotes
the matrixwith first row as 1 2 3 4, second row
echoon as 5 6 7 8, third row as 1 1 2 3.
a= [1 4 1];
b=[6; 7; 8];  To extract a submatrix B consisting of
% transpose
c=a' row 1 and 3, columns 2 and 4, we use
% length of a vector the command B=A([1 3], [2 4]).
length(a)
% component wise power
d= a.^(0.5)  To interchange rows 1 and 3 of A use
% component wise square the row indices together with colon
e=a.*a
% dot product operator: C=A([3 2 1], :). The colon
f=a*b operator : stands for all columns or all
% component wise division rows.
f= a./b'
% cross product
g=cross(a,b)  A(:) creates a vector version of a matrix
% unique- gives the values of A.
array without repetitions
uni=unique(a)  To delete a row(column) use the empty
% sorting in ascending order
ascend=sort(a) vector operator [ ].
% setdiff gives elements in a not
in b Example: A(:, 2)=[].
set= setdiff(a,b')
echooff  To insert the second column back.

Example: A=*A(:,1) *2 6 1+’ A(:,3) A(:,4)+


Try yourself:
 Let d= [1 2 3]; D= diag(d) is a diagonal
Let x = [3 2 6 8]' and y = [4 1 3 5]'. matrix with diagonal entries in d.
Add x and y and then find sum of elements of
% Matrix operations
resulting vector. %
echoon
MATRICES OPERATIONS A=[1 2 3 4; 5 6 7 8; 9 10 11 12]

Formation of matrices: % To interchange rows 1 and 3 of A


C=A([3 2 1],:)
 Commas or spaces are used to separate
elements in a specific row and % To create the vector version of A
D=A(:)
semicolon are used to separate
individual rows. % To delete column 2 of A
 Alternately, pressing return or enter key A(:,2)=[]
while entering a matrix also tells %To find diag of A
MATLAB to start a new row. D=diag(A)
echooff
Scalar Array Mathematics:

 Addition, subtraction, multiplication(.*), %Computingcputime for the program.


division by a scalar(./) applied to all
T=cputime;
elements in the array/ matrix.
A=[1 3 6; 2 7 8; 0 3 9]
Array – Array Mathematics & Matrix Functions
%Order of A can be found out
size(A) order of matrix order= size(A)

%Transpose of A
A’ transpose of matrix B=A'

A(:,3) third column of A %3rd column of A


thirdcolumn=A(:,3)

A(1,:) first row of A %First row of A


firstrow=A(1,:)
A(1,:)+A(3,:) first row+third row of A %C=A+B adds the matrices A and B
C=A+B
C=A+B addition of matrices
%D=A*B gives the product of the
matrices A and B
C=A*B multiplication of matrices D=A*B

%A^-1
inv(A) inverse of matrix invA=inv(A)

%Determinant of A
chol(A) cholesky decomposition of a detA=det(A)
positive definite matrix A
det(A) determinant of matrix %Rank of A
rank(A)

rank(A) rank of matrix %Trace of A gives the sum of diagonal


elements of A
tr=trace(A)
eye(n) identity matrix of order n
%Identity matrix of order 3 is
trace(A) trace of matrix generated now
identity=eye(3)

zeros(n,m) nxm zero matrix %Generating a zero matrix of order 2


by 3
zero=zeros(2,3)
rand(n,m) nxm matrix having random entries
%Matrix of order 3 x 4 with random
entries
Random=rand(3,4)
diag(v) produces a diagonal matrix whose  x=inv(A)*y (computes inverse explicitly)
elements are components of
vector v  x=A\y (uses LU decomposition)
eig(A) eigen values of matrix A
%Solving Ax=y
[V,D]=eig(A) produces V matrix whose A=[1 3 4; 5 7 8; 2 3 5]
columns are eigenvectors and the y=[10; 9; 8]
diagonal matrix D whose values
are eigenvalues of the matrix A %computing inverse of a matrix A
Inverse=inv(A)
Identity=A*inv(A)
x=inv(A)*y
A=VDV^{-1}: V*D/V eigenvalue-eigenvector x1=A\y
decomposition of a diagonalizable
matrix A is calculated
Computing the CPU time (in seconds):

 T=cputime;
[L,U]=lu(A) LU decomposition
 Operations….
[Q,R]=qr(A) QR decomposition
 TT=cputime-T;

%Generating a diagonal matrix. LOOPS AND LOGICAL STATEMENTS:


v=[3 2 1 8];
M=diag(v)

% Extracting lower and upper triangular


parts of a matrix. Multiple for loops :
B=[3 1 2 ; -1 3 4 ; -2 -1 3]
L= tril(B) for i=1:100
U = triu(B)
for j=1:50
%Eigenvalues of matrix A
eigv=eig(A) for k=1:50
[V,D]=eig(A)
a(i ,j)=b(i,k)*c(k,j)+a(i,j);
% Extracting orthonormal and upper
triangular parts of a matrix. end
[Q,R]=qr(A)
Q*Q' end
Try yourself:
end
Generate two random matrices of order 3x3
and find their product and inverse of product. While

Solution of linear equations : Ax=y while( condition)

Assuming the system has a unique solution, we statements


can obtain x as: end
x = 0;

for k = 2:1000
if, elseif, else, end
x(k) = x(k-1) + 5;
if(condition #1)
end
statement #1
Change the first line to preallocate a 1-by-1000
elseif(condition #2)
block of memory for x initialized to zero.
statement #2
This time there is no need to repeatedly
else reallocate memory and move data as more
statement #3 values are assigned to x in the loop:

end x = zeros(1, 1000);

for k = 2:1000
Try yourself:
x(k) = x(k-1) + 5;
Given x = 1:10 and y = [3 1 5 6 8 2 9 4 7 0],
execute and interpret the results of the following end
commands:
1. x( (x < 2) | (x >= 8) ) VECTORIZATION
2. y( (x < 2) | (x >= 8) )
3. x(y < 0). One way to make your MATLAB programs run
faster is to vectorize the algorithmsyou use in
constructing the programs.
PREALLOCATING ARRAYS
A simple example involves creating a table of
for and while loops that incrementally increase logarithms.
the size of a data structure each time through
x=0.01;
the loop can adversely affect performance and
memory use. Repeatedly resizing arrays often for k = 1:1001
requires that MATLAB spend extra time looking
y(k) = log10(x);
for larger contiguous blocks of memory and
then moving the array into those blocks. You x = x + .01;
can often improve on code execution time by
end
preallocatingthe maximum amount of space
that would be required for the array ahead of A vectorized version of the same code is:
time.The following code creates a scalar
variable x, and then gradually increases the size x = .01:.01:10;
of x in a for loop instead of preallocating the y = log10(x);
required amount of memory at the start:
% Loops and logical statements % A loop free version-vectorization is
as follows:
%for loop %--------------------------------------
%----------- k=1:10;
A=sin(k)'*cos(k);
%Compute the first 6 terms of the
Fibonacci sequence %while loop
%-------------
%f_i=f_{i-1} + f_{i-2}
%echo on f(1)=0; f(2)=1; k=3;
f(1)=0; f(2)=1; while k <=6
for i=[3 4 5 6] %for i=3:6 f(k)=f(k-1)+f(k-2);
f(i)=f(i-2)+f(i-1); k=k+1;
end end
break % if / else if
%--------------------
% Ex 2 for for loop % Roots of the polynomial ax^2+bx+c
%-------------------- a=input('Enter value of a =');
% Generating sine function for 11 evenly b=input('Enter value of b =');
placed points c=input('Enter value of c =');

for n=0:10 if a~=0


x(n+1)=sin(pi*n/10); sq=sqrt(b*b-4*a*c);
end x(1)=0.5*(-b+sq)/a
x(2)=0.5*(-b-sq)/a
%break elseif b~=0
% Ex3 for for loop-nested for loops x(1)=-c/b
%-------------------------- elseif c~=0
% Creating the Hilbert matrix. disp('Impossible equation')
else
H=zeros(5); disp('The given equation is an
for k=1:5; identity')
for l=1:5; end
H(k,l)=1/(k+l-1);
end
end

%The first co%A=[a_{kl}], where


%a_{kl}=sin(k) cos(l). We will compute FUNCTION SUBROUTINES
entries of A by using nested loops
% and also by vectorization.  Special type of m file.
A=zeros(10);  Receives input data through input
for k=1:10
for l=1:10
argument list.
A(k,l)=sin(k)*cos(l);
end  Returns results to the caller through an
end output argument list.
%The distance between two points in 2D SUBPLOTS
plane.
Subplot can be used for plotting more than one
%Definition of variables: set of axes in a single figure. Subplots are
%ax= x position of the point a
%ay= y position of the point a created with the help of the command
%bx= x position of the point b
%by= y position of the point b subplot(m,n,p)
%result=distance between two points
This creates m x n subplots in the current figure,
%Get input data arranged in m rows and n columns, and selects
disp('Calculate the distance between two
points') subplot p to receive all current plotting
ax=input('Enter x value of point a: '); commands.
ay=input('Enter y value of point a: ');
bx=input('Enter x value of point b: '); Example: subplot(2,3,4)
by=input('Enter y value of point b: ');

%Evaluate function This will create six subplots in the current


result=dist2(ax,ay,bx,by) figure and will make subplot 4 (the lower left
******************************** one) as the current subplot.
function distance=dist2(x1,y1,x2,y2)
%Output argument is distance which is
the distance between (x1,y1)and (x2,y2)
distance=sqrt((x2-x1).^2+(y2-y1).^2); %Plotting graph using SUBPLOT
%Notice that the function has 4 input
arguments and 1 output argument. %function y = x/(1+x^2)

Try yourself: k = 0;
for n=1:3:10
Calculate distance between x =(1,4) and y=(5,9). n10 = 10*n;
x = linspace(-2,2,n10);
y = x./(1+x.^2);
PLOTTING TOOLS (2D) k = k+1;
subplot(2,2,k)
Plot(x,y,’r’) co-ordinates x-y, colour-red plot(x,y,'r')
title(sprintf('Graph %g. Plot based
axis([ a,b,c,d]) dimension of the box holding the plot upon n = %g points.'...
[a b c d]=[xmin xmax ymin ymax] , k, n10))
xlabel('x')
xlabel(‘ ’) label x axis ylabel('y')
axis([-2,2,-.8,.8])
ylabel(‘ ’) label y axis grid
pause(3);
legend(‘ ’) distinguish various curves in same end
plot
grid adds grid lines to graph Try Yourself:

pause( ) holds on to current graph till you Plot y = sin x, 0<x<pi taking 100 linearly spaced
press enter points in the given interval.
Pause(n) holds on to current graph for n
seconds
% Graphs of two ellipses in the same subplot creates an array of plots in same window
%figure
loglog plot using log-log scales
% x(t) = 3 + 6cos(t), y(t) = -2 +9sin(t)
% x(t) = 7 + 2cos(t), y(t) = 8 +6sin(t) semilogx plot using log scale on the x-axis
% There are several commands to enhance
semilogy plot using log scale on the y-axis
the readability of the graph.

%First of all note that the equations are


surf 3-D shaded surface graph
converted into parametric form.
surfl 3-D surface graph with lighting
t = 0:pi/100:2*pi;
x1 = 3 + 6*cos(t); mesh 3-D mesh surface
y1 = -2 + 9*sin(t);
x2 = 7 + 2*cos(t);
y2 = 8 + 6*sin(t); PLOTTING TOOLS (3D)
h1 = plot(x1,y1,'r',x2,y2,'b');

% Plot colours: y=yellow, m = magenta,


plot3(x,y,t) 3D plot
c=cyan, r=red, g=green,b=blue, w=white, set(h,’LineWidth’,1.25) set linewidth
k=black.
set(h,’’FontSize’,11) set fontsize
set(h1,'LineWidth',1.25) colormap {colour} to apply desired colour
% To set the thickness of the plotted
curves to a width of our choice.
shading interp shading after interpolation
axis('square')
% To force the axes to have square
dimensions or else circular curves maynot
necessarily look circular. view([25,15,20]) To set viewing angle

legend('ellipse1', 'ellipse2')
xlabel('x')
ILLUSTRATION OF MESH GRID:
h = get(gca,'xlabel');
%gca= get current axis; the axis targetted
%here is x-axis. % Illustration of meshgrid
x=-1:0.05:1;
set(h,'FontSize',12) y=x;
set(gca,'XTick',-4:10) [xiyi]=meshgrid(x,y);
% Specify font size and tick marking along zi=yi.^2-xi.^2;
the current axis. mesh(xi,yi,zi)
axisoff
ylabel('y') % To plot the graph of the mesh surface
h = get(gca,'ylabel'); along with contour plot beneath the
set(h,'FontSize',20) % plotted surface:
set(gca,'YTick',-12:2:14) meshc(xi,yi,zi)
title('Graphs of (x-3)^2/36+(y+2)^2/81 = 1
and (x-7)^2/4+(y-8)^2/36 = 1.')
h = get(gca,'Title');
set(h,'FontSize',12)
grid
POLYNOMIALS Try yourself:

Solve the polynomial x^3 - 6x^2 + 11x – 6 and


polyval evaluates polynomial calculate its first derivative and roots of the
derivative.
roots(p) computes zeros of p(x)
Fzero FOR ZEROS OF NON-LINEAR EQUATIONS
poly(r) reconstructs polynomials from the
roots  fzero(fun,x0) adopts Dekker-Brent
conv(p1,p2) gives the coefficients of the method to compute the zero of the
polynomial given by the product of
function fun, where fun can be defined
two polynomials whose coefficients
are contained in the vectors p1 and as an inline function or in a .m file.
p2.
Syntax:
polyder(p) gives the coefficient of p’(x)
f=inline(‘fun’,’variable’); x0=..
polyint(p) gives coefficients of integral of p(x)
[alpha,res,flag,iter]=fzero(fun,x0)

% Polynomials........... where alpha=root, res=residual, iter= number of


iterations, flag is negative means fzero can’t
% Values: find the zero.
p=[1 0 0 0 0 3 0 -1]; % polynomial
x^7+3x^2-1
x=[-1:0.25:1]; % equispaced abscissae
%x_k=-1+k*0.25 for k=0,...8. SYMBOLIC TOOLS
y=polyval(p,x) % Values of polynomial
After defining a function,
% Zeros:
p=[1 -6 11 -6]; format long; % x^3- diff(f) Differentiation of f
6x^2+ 11 x -6
roots(p)
int(f) Indefinite integration of f
%Coefficients of polynomial p1*p2
p1=[1 0 0 0 -1] % p1(x)=x^4-1 taylor(f,x,r) Taylor expression of f till r terms
p2=[1 0 0 -1] % p2(x)=x^3-1 about x=0
p=conv(p1,p2) % Gives coefficient of
p1*p2
Try yourself:
% Coefficients of p'(x), integral of
p(x) Generate Taylor expression of f(x)=sin(x) upto 6
terms at x=0.
derivative=polyder(p1)
integral=polyint(p1)
Numerical Integration (composite computed so as to ensure that
quadrature error is below 10-3.
midpoint quadrature formula)
 quadl(fun,a,b,tol)specifies a different
%Numerical integration using composite tolerance level.
midpoint formula:

%Illustration of the use of inline %Gauss-Lobatto quadrature rule


functions
a=input('a='); %specify limits of
a=input('a='); integration
b=input('b='); b=input('b=');
M=input('number of subintervals=');
%fun=inline('1./x','x') %MATLAB will
%f='5'; %Integrating a constant evaluate the expression component by
function component on the vector
%f=inline('1+x','x')
% f=inline('x.^2-10.*x+15','x') fun=inline('1./(1+x.^2)','x')
f=inline('sin(x)','x')
%f=inline('1./(1+x.^2)','x') int=quadl(fun,a,b) %integrates fun
with tolerance 10^-3.
function Imp=midpointc(a,b,M,f)
H=(b-a)/M;
%tol=input('tol=')
x=linspace(a+H/2,b-H/2,M);
%int1=quadl(fun,a,b,tol)
fmp=feval(f,x);

Imp=H*sum(fmp)
Try yourself:
Try yourself:
Solve using Gauss Quadrature formula
Solve using composite midpoint quadrature ∫
formula:

∫ Newton’s method for


Non-Linear Systems
Gauss-Lobatto Quadrature Formula
 To compute the roots of nonlinear
 We use an inbuilt function systems of the following form:
quadltocomputean integral using f1(x1,x2,….,xn)=0,
Gauss-Lobatto quadrature formula. f2(x1,x2,….,xn)=0,
f3(x1,x2,….,xn)=0,
 The function is defined as an inline
---------------------,
object.
fn(x1,x2,….,xn)=0,
 Call quadl(fun,a,b). (fun-function, a ,b –
limits of integration) where fi are nonlinear functions, using
Newton’smethod, use
 The number of subintervals is not
requested as it is automatically zero=fsolve(‘fun’,x0)
This allows the computation of one zero
of the nonlinear system defined ORDINARY DIFFERENTIAL EQUATIONS
through fun starting from x0 as initial
guess.
 Write the differential equation (s) as a
% Newton's method to solve a system of set of ODEs.
nonlinear equations: x’=f(x,t)
where x = *x1 x2 …… xn+’
% x^2 + y^2=1
% sin(pi*x/2)+y^3=0
 Use built-in ODE solvers ‘ode23’ or
% Solutions are (0.4761, -0.8794) and (- ‘ode45’ to solve the equations.
0.4761,0.8794)
[t, sol+ = ode23(‘ur_func’,tspan, x0)
x0=[1 1]; % Initial iterate
alpha=fsolve('systemnl',x0) where :
t= time vector; sol= solution matrix;
tspan= time span; x0= initial conditions
General Instructions for
Numerical Analysis Programs Ode23 Uses Runge-Kutta scheme of
order 2 and 3.
Ode45 Uses Runge-Kutta scheme of
 Declare the array variables to zero.
order 4 and 5.
 Use clear all statement in the beginning Ode113 Uses explicit predictor -
of the code. corrector method with
 Use long double for real arrays. variable order 1 and 13.
 Declare the matrix as “sparse” in case Ode15s Uses Implicit multistep
you are working with a sparse matrix to method with variable order 1
to 5.
save memory and computation time.
Ode23s Uses Runge-Kutta scheme of
For ex. a sparse matrix of dimension order 2 and 3.
10* 100 is initialized by A =
sparse(10,100). Huge identity matrices
% to solve the first order
can be also declared as sparse matrix by differential equationdx/dt=x+t
using A=speye(100). % initial condition x(0)=0
 A full matrix A can be transformed to a
functionxdot=simpode(t,x)
sparse matrix by using the command
A=sparse(A). %simpode : computes xdot=x+t
 In case, a sparse matrix needs to be %call syntax :xdot=simpode(t,x)
transformed to a full matrix, use the
command A=full(A). xdot=x+t;
tspan=[0 2]; %specify timespan
 Use vectorization as far as possible. x0=0; % specify x0
 Assign space in memory for arrays and
[t,x]=ode23('simpode',tspan,x0)
matrices in the beginning. %now execute ode23
Try yourself: c) Divide each element of y by the
corresponding element in x.
Solve the following differential equation:
; y(0) = 1 d) Multiply each element of x by the
corresponding element in y and call
the result z.
%to solve second order non linear
differential equation e) Sum up the elements in z and
assign the result to a variable called
%write a function to compute the new
state derivatives
w.

functionzdot=pend(t,z) f) Compute (x-y)/w and interpret the


result.
%call syntax: zdot=pend(t,z)
%inputs are: t=time
2. Evaluate the following expressions:
z=[z(1);z(2)]=[theta;thetadot] a) round(6/9)
%output is: zdot=[z(2);-w^2*sin z(1)] b) floor(6/9)
c) ceil(6/9)
wsq=1.56; %specify a value of w^2
zdot[z(2); -wsq*sin(z(1))]
3. Plot the functions x, x^3, e^x and
%use ode23 ode 45 for solution : e^(x^2) over the interval 0 < x < 4.
tspan =[0 20];z0=[1;0]; %assign values to
tspan,z0
[t,z]=ode23('pend',tspan,z0) % run ode23 4. Given the array A = [2 4 1; 6 7 2; 3 5
x=z(:,1);y=z(:,2); %x=column 1 9], provide the commands needed
of z, y=column 2 to:
a) Assign the first row of A to a vector
plot(t,x,t,y) %plot t vs x x1 = [1 2 3].
and t vs y
b) Assign the last 2 rows of A to a
xlabel('t'),ylabel('x and y')%add axis
labels
matrix Y = [2 3 1; 5 3 2].

figure(2) %open a new c) Compute the sum over the columns


figure window of A and also over the rows of A.
plot(x,y) %plot phase
portrait 5. Given the vector x = [1 8 3 9 0 1],
xlabel('displacement'),ylabel('velocity') create a short set of commands that
title('phase plane plot') %put a title
adds up the values of the elements of x.

6. Find the numerical solutions to the


EXERCISES following initial value problems (IVP)
a) dy/dt=1/(t+y+1) , y(0)=0 , 0<t<1
1. Let x = [3 2 6 8] and y = [4 1 3 5].
a) Add the sum of the elements in x to b) dy/dt=loglog(4+y^2), y(0)=1, 0<t<1.
y.
7. Find the approximate solution x(1.1)
b) Raise each element of x to the of the initial value problem
power specifed by the corresponding dx/dt = 3t-x/t ; x(1)=2.
element in y.

You might also like