You are on page 1of 27

Tutorial problems Introduction to MATLAB

Problem1 A simple sine plot: plot y = sin x, 0 <= x <= 2*pi, taking 100 linearly spaced points in the given interval. Label the axes and put a title Solution 1: MATLAB Program
x=linspace(0,2*pi,100); figure(1) plot(x,sin(x)) xlabel('x'), ylabel('sin(x)') title('sine plot') grid on

Problem 2 An exponentially decaying sine plot: plot y = e-0.4x sin(x), 0 <= x <= 4*pi, taking 10, 50, and 100 points in the interval. Solution 1: MATLAB Program
x =linspace(0,4*pi,10); % 10 points y = exp(-0.4*x).*sin(x); plot(x,y) hold on x =linspace(0,4*pi,50); % 50 points y = exp(-0.4*x).*sin(x); plot(x,y) hold on x =linspace(0,4*pi,100); % 100 points y = exp(-0.4*x).*sin(x); plot(x,y) xlabel('X') ylabel('Exponential decay function')

Problem 3: Draw a circle with given radius, using Script Programming in MATLAB Solution 3 MATLAB Program % circle a script file to draw a unit circle r = input(Enter the radius of the circle) theta = linspace(0,2*pi,100); x = r * cos(theta) ; y = r * sin(theta) ; plot(x,y) axis(equal) title(Circle with unit radius)

Problem 4 Write a function that outputs a conversion table for celsius and fahrenheit temperatures. Input of the function should be two numbers Ti and Tf specifying the lower and upper range of the table in celsius. 9 Hint: F = C + 32 5 Solution 4 MATLAB Program
function temptable = ctof(tinitial, tfinal); % CTOF : function to convert temperature from C to F % Call syntax : % temptable = ctof(tinitial, tfinal); % ------------C = [tinitial:tfinal]; F = (9/5)*C + 32; temptable = [C; F]';

Problem 5 Wrtie a function factorial to compute the factorial n! for any integer n. The input should be the number n and the output should be n!. You might use a for loop or a while loop to do the calculations. (Note: you can also use the built in function prod to calculate a factorials) Solution 5: MATLAB Program
function factn = factorial(n); % Factorial : function to compute a factorial n! % call syntax : % factn = factorial(n); % ---------------------factn = 1; for k = n:-1:1 factn = factn*k; end

Problem 6: Wrtie a function file crossprod to compute the cross product of two vectors u, and v, given u = (u1, u2, u3), v = (v1, v2, v3), and u X v = (u2v3 u3v2, u3v1 u1v3, u1v2 u2v1). Check your function by taking cross products of pair of unit vectors: (i, j), (j, k) etc . [i = (1 0 0), j = (0 1 0), k = (0 0 1). Do not use the built in function here. Solution 6: MATLAB Program
function w =crossprod(u,v); % Cross product : function to compute w u X v for vectors u and v % Call syntax : % w = crossprod(u,v); % ----------------------if length(u) > 3 | length(v) > 3 % check if u OR v has > 3 elements error('Ask Euler. This cross product is beyond me') end w = [u(2) * v(3) - u(3) * v(2); % first element of w u(3) * v(1) - u(1) * v(3); % second element of w u(1) * v(2) - u(2) * v(1)]; % third element of w

Problem 7: Write a function to compute the sum of a geometric series 1 + r + r2 + r3 + . + rn for a given r and n. Input to the function must be r and n and output must be the sum of the series. Solution 7: MATLAB Program
function s =gseriessum(r,n); % GSSERIESSUM : function to compute the sum of a geometric series % The series is 1+r+r^2+r^3+ ------ +r^n % Call syntax : % s = gseriessum(r,n); % ----------------------nvector = 0 : n; series = r.^nvector; s = sum(series);

Problem 8: The interest you get at the end of n years, at a flat annual rate of r%, depends on how the interest is compunded. If the interest is added to your account k times a year, and the principal amount your invested is X0, then at the end of n years you would have X = X0 (1 + r / k )kn amount money in your account. Write a function to compute the interest (X X0) on your account for a given X, n, r, and k. Solution 8: MATLAB Program
function [capital, interest] = compound(capital, years, rate, timescomp); % compound : function to compute the compounded capital and the interest % Call syntax : % [capital, interest] = compound(capital, years, rate,timescomp) % ----------------------X0 = capital; n = years; r = rate; k = timescomp; if r > 1 disp('check your interest rate. For 8 % enter 08, not 8.') end capital = X0*(1 + r/k) - (k*n); interest = capital - X0;

Problem 9: Enter following three matrices, 2 6 1 2 5 A = B = C = 3 9 3 4 5 1. Compute D = A + B + C 2. Compute E = A*B*C 3. Compute F = C*B*A and compare E and F Solution 9: MATLAB Program
% A B C D E F Enter matrices A, B, C = [2 6; 3 9]; = [1 2; 3 4]; = [-5 5; 5 3]; = A + B + C = A*B*C = C*B*A

5 3

Problem 10 Create a big matrix with submatrices : The following matrix G is created by putting matrices A, B, and C given. Do the following operations on matrix G created above
= 2 3 0 0 0 0 6 9 0 0 0 0 0 0 1 3 0 0 0 0 2 4 0 0 0 0 0 0 5 5 0 0 0 0 5 3

1. Delete the last row and last column of the matrix 2. Extract the first 4 X 4 submatrix from G 3. Replace G(5,5) with 4
Solution 10: MATLAB Program Problem 11 The following data is obtained from an experiment aimed at measuring the spring constant of a given spring. Different masses m are hung from the spring and the corresponding delfections of the spring from its unstreached configurtation are measured. Find value of stiffness coefficient of spring M (g) 5.0 10.0 20.0 50.0 100.0 (mm) 15.5 33.07 53.39 140.24 301.03 Solution 11: MATLAB Program
% Spring constant fron experimental data m = [5 10 20 50 100]; g = 9.81; d = [15.5 33.07 53.39 140.24 301.03]; F = m /1000*g; a = polyfit(d,F,1); d_fit = 0:10:300; F_fit = polyval(a, d_fit); plot(d,F,'o',d_fit,F_fit) xlabel('Displacement (mm)') ylabel('Force (N)') k = a(1); text(100,0.32,['\leftarrow Spring Constant K = ', num2str(k)]);

Problem 12 The following table shows the time versus pressure variation readings from a vacuum pump. Fit the curve, P(t) = P0 e t/T t 0 0.5 1.0 5.0 10.0 20.0 P 760 625 528 85 14 0.16 Solution 12: ^ t Taking log of both sides, we have ln( P ) = ln( P 0 ) or P = a 1 t + a 0 T Where P = ln( P ),
^

a1 = 1 / T ,

and

a 0 = ln( P 0 )

MATLAB Program
% EXPFIT : Exponenetial curve fit % For the following data for (t,p) fit % an exponential curve % P = P0 * exp(-t/tau) % Problem is solved by taking log and % then using a linear fit (1st order % polynomial % Orginal Data t = [0 0.5 1 5 10 20]; p = [760 625 528 85 14 0.16]; % Prepare new data for linear fit tbar = t; pbar = log(p); % Fit a 1st order polynomial % thorugh (tbar, pbar) a = polyfit(tbar,pbar,1); % Evaluate constant P0 and tau P0 = exp(a(2)); tau = -1/a(1); %plot new curve and the data on linear scale tnew=linspace(0,20,20); pnew=P0*exp(-tnew/tau); figure(1), plot(t,p,'o',tnew,pnew), grid xlabel('Time (Sec)'), ylabel('Pressure (torr)') % Plot the new curve and the data on semilog scale lpnew=exp(polyval(a,tnew)); figure(2), semilogy(t,p,'o',tnew,lpnew), grid xlabel('Time (Sec)'), ylabel('Pressure (torr)')

Problem 13 Find solution of the following set of linear algebraic equations as, x + 2 y + 3z = 1 3x + 3 y + 4 z = 1

2 x + 3 y + 3z = 2 Write the equations in matrix form and solve for x = [x y z]T using left division Solution 13: MATLAB Program
% Tutorial Problem 13 % Solution of algebraic equations A = [1 2 3; 3 3 4; 2 3 3]; B = [1 1 2]'; X = inv(A)*B; disp('Roots of equations are'),X

Problem 14: Figure shows the loading on a semicircular member, The radius of semicircular member is 25 inches. Write a MATLAB program to plot the internal forces, namely the axial forces, shearing forces and bending moment as functions of for -90 < < 90

300 lb 25 inch 200 lb C

200 lb

Solution 14: For -90 < < 90, C = 200 sin + 150 cos ; V = 200 cos - 150 sin ; M = -200 r sin + 100 r ( 1- cos ) Matlab Program
% Variation o axial force, shearing force and bending moment alpha = -90:90; alpha = pi*alpha/180; r = 25; C = 200.*sin(alpha) + 150.*cos(alpha); V = -200.*cos(alpha) + 150.*sin(alpha); M = -200.*r.*sin(alpha)+ 100.*r.*(1-cos(alpha)); figure(1) subplot(2,1,1), plot(alpha*180/pi,C,alpha*180/pi,V), grid xlabel('Alpha in (deg)'), ylabel('Axial and Shearing Force (lb)') axis([-90,90,-400,400]), legend('Axial Force','Shearing Force') subplot(2,1,2), plot(alpha*180/pi,M) xlabel('Alpha in (deg)'), ylabel('Bending Moment (lb-inch)'), grid axis([-90,90,-5000,10000])

Problem 15: The motion of a particle is defined by equation, X = 35 t2 110 t Y = 115 t2 42 t3 Where, X and Y displacmenet of the particle, t is time in sec For interval 0 < t < 25 s, write a MATLAB program to plot 1. the path of the particle in XY plane 2. the components of velocity Vx and Vy and magnitude of the velocity V 3. the components of the acceleration Ax and Ay and magnitude of the acceleration Solution 15: MATLAB Program
% Tutorial 15 t = 0:0.5:25 X = 35*t.^2-110*t; Y = 115*t.^2-42*t.^3; Vx = 70*t-110; Vy = 230*t-126*t.^2; V = sqrt(Vx.^2+Vy.^2); Ax = 70; Ay = 230-252*t; A = sqrt(Ax.^2+Ay.^2); figure(1) subplot(2,2,1), plot(X,Y), grid xlabel('X (mm)'),ylabel('Y (mm)') subplot(2,2,2), plot(t,X,t,Y), grid xlabel('Time (sec)'),ylabel('X & Y (mm)') legend('X (mm)','Y (mm)') subplot(2,2,3), plot(t,Vx,t,Vy,t,V), grid xlabel('Time (sec)'),ylabel('Vx, Vy, V (mm/s)') legend('Vx (mm/s)','Vy (mm/s)', 'V (mm/s)') subplot(2,2,4), plot(t,Ax,t,Ay,t,A), grid xlabel('Time (sec)'),ylabel('Ax, Ay, A (mm/s)') legend('Ax (mm/s)','Ay (mm/s)', 'A (mm/s)')

Problem 16: The acceleration due to gravity due to earth at any height h above the surface of the earth is given by, GM g = m / s2 2 (R + h) Where, G the gravitational constant ( 6.67 X 10-11 Nm2/kg2) M mass of the earth (5.99 X 1024 kg) R mean radius of the earth (6372 km) h height above the surface of the earth (m) Write a MATLAB program to calculate and plot the acceleration due to gravity for 0 < h < 45000 km in 500 km increments Solution 16: MATLAB Program
% Tutorial 16 % Shows variation of g with height upto 45000 km G = 6.67E-11; M = 5.99E24; R = 6372; h = 0:0.5:500000; g = G.*M./(R + h).^2; g = g/1E6; figure(1) plot(h/1000,g), grid xlabel('Height above a earth surface (km)') ylabel('Acceleration due to gravity (m/s^2)') axis([0, 50, 0, 10])

Problem 17:

The satellite orbit in polar coordinates is given by, r =

P 1 cos( )

r distance of satellite from the center of the earth angle of the satellite from center of the earth P a parameter specifying the size of the orbit a parameter specifying eccentricity of the orbit Write a MATLAB program to plot the orbit of a satellite for = 0, 0.25, 0.5, and 0.75
Solution 17: MATLAB Program
% Tutorial 17 P = 1100; eps = 0.0; theta = 0:2*pi/200:2*pi; r = P./(1-eps.*cos(theta)); figure(1) subplot(2,2,1), polar(theta,r) title('\bf orbit for \epsilon = 0.0') eps = 0.25; r = P./(1-eps.*cos(theta)); subplot(2,2,2), polar(theta,r) title('\bf orbit for \epsilon = 0.25') eps = 0.5; r = P./(1-eps.*cos(theta)); subplot(2,2,3), polar(theta,r) title('\bf orbit for \epsilon = 0.50') eps = 0.75; r = P./(1-eps.*cos(theta)); subplot(2,2,4), polar(theta,r) title('\bf orbit for \epsilon = 0.75')

Problem 18: A motor of weight W is supported by four springs with spring constant of 400 lb/in each. The unbalance of the motor is found to be equivalent to a weight of 0.05 lb located 5 in. from the axis of rotation. If the motor is constrained to move vertically, write a MATLAB program to calculate and plot the amplitude of the vibration and maximum acceleration of the motor for motor speeds from 0 to 1200 rpm. Weight of motor W = 35 lb. Solution 18: Equation of magnification factor in case of unbalance is given by Pm / K 2 xm = Pm = mr f 2 1 ( f / n ) MATLAB Program
% Tutorial 18 W = 35; g = 32.2; mW = W / g; % Mass of rotor in lb ks = 400 * 12; % One spring stiffness m = 0.05 / g; % mass of unbalance r = 5/12; % radius of rotation k = 4*ks; % total stiffness of all spring omega_n2=k/mW; % square of natural frequency omega_f=[0:5:1200]; % variation of motor speed omega=omega_f*2*pi/60; Pm=m*r*omega.^2; % unbalance force due to rotation xm=(Pm/k)./(1-omega_f.^2/omega_n2); am=omega_f.^2.*xm; % acceleration in ft/s^2 amp=xm*12; % amplitude in inches z=[omega_f;amp;am]; figure(1) subplot(2,1,1), plot(omega_f,amp),grid xlabel('Motor Speed (rpm)'),ylabel('Amplitude of vibration (inch)') subplot(2,1,2), plot(omega_f,am),grid xlabel('Motor Speed (rpm)'),ylabel('Max. Motor Acceleration (ft/s^2)')

Problem 19:
Figure shows an approximate model of a vehicle by the spring and dashpot system. The system moves with a speed of V over a road with a sinusoidal cross section of amplitude dm and wavelength l. Write a MATLAB program to determine and plot the amplitude of the displacement of the mass relative to the road as a function of the speed V for damping factors c/cc = 0.1, 0.3, 0.5, and 0.7.

m K C
x
Equilibrium

K(x-- st)

C(x-)

l
Solution 19:

Equation of motion of vehicle is Amplitude ratio is given by, Where, n = K / m


um

m
=

d 2x dx +c + kx = m 2 m sin( t ) = p m sin( t ) 2 dt dt ( / n ) 2
[1 ( / n ) 2 ] 2 + [ 2 ( c / c c )( / n )] 2

m
v l

= 2

MATLAB Program
% Tutorail 18 op = [0:0.05:10]; Cr01 = 0.1; den = sqrt((1-op.^2).^2+(2*Cr01.*op).^2); num = op.^2; ratio01 = num./den; Cr02 = 0.3; den = sqrt((1-op.^2).^2+(2*Cr02.*op).^2); num = op.^2; ratio02 = num./den; Cr03 = 0.5; den = sqrt((1-op.^2).^2+(2*Cr03.*op).^2); num = op.^2; ratio03 = num./den; Cr04 = 0.7; den = sqrt((1-op.^2).^2+(2*Cr04.*op).^2); num = op.^2; ratio04 = num./den; figure(1) plot(op,ratio01,op,ratio02,op,ratio03,op,ratio04), grid xlabel('Speed ratio'),ylabel('Ratio of Relative Displacement')

Problem 20: Determine the eigenvalues and eigenvectors of AB using MATLAB 5 7 1 3 3 0 2 1 2 1 2 4 1 2 5 4 A= B = 3 2 7 1 2 6 1 1 0 6 4 1 1 2 3 4 Solution 20
% Tutorial 20 A =[3 0 2 1; 1 2 5 4; 7 -1 2 6; 1 -2 3 4]; B =[1 3 5 7; 2 -1 -2 4; 3 2 1 1; 4 1 0 6]; C=A*B; V=eig(C) [Q d]=eig(C)

Problem 21: Write a program to plot a non-dimensional response magnitude and phase response for a system with harmonically excited base

x(t)

y(t)

Solution 21:

Magnitude of frequency response is given by G ( j ) =

1
2 2 2 (1 ( + 2 ) n n 1/ 2

Phase Response
2 2 1 n ( ) = tan 2 1 + 2 n n

MATLAB Program
% Tutorial 21 zeta=[0.05; 0.1; 0.15; 0.25; 0.5; 1.25; 1.5]; r = [0:0.01:3]; for k=1:length(zeta) G(k,:)=sqrt((1+(2*zeta(k)*r).^2)./((1-r.^2).^2+(2*zeta(k)*r).^2)); phi(k,:)=atan2(2*zeta(k)*r.^3, (1-r.^2+(2*zeta(k)*r).^2)); end figure(1) subplot(2,1,1), plot(r,G), grid legend('\zeta_1=0.05','\zeta_2=0.1','\zeta_3=0.15',... '\zeta_4=0.25','\zeta_5=0.5','\zeta_6=1.25','\zeta_7=1.5') xlabel('\omega/\omega_n'),ylabel('|x(i\omega)|A') subplot(2,1,2), plot(r,phi), grid legend('\zeta_1=0.05','\zeta_2=0.1','\zeta_3=0.15',... '\zeta_4=0.25','\zeta_5=0.5','\zeta_6=1.25','\zeta_7=1.5') xlabel('\omega/\omega_n'),ylabel('\phi (\omega)')

Problem 22: An analytical expression for the response of undamped single degree freedom system to given initial velocity and displacement is given by, x (t ) = Ce nt cos( d t )
x + v0 x + v Where C x0 + n 0 = tan 1 n 0 0 d = 1 2 n x d d 0 Plot the response of system for n = 5 rad/s, = 0.05, 0.1, 0.2, subjected to initial conditions x(0) = 0, x(0) = v0 =60 cm/s
2 2

Solution 22:
% Tutorial 22 clear all wn = 5; zeta = [ 0.05; 0.1; 0.2]; x0 = 0; v0 = 60; t0 = 0; deltat = 0.01; tf =6; t = [0:deltat:tf]; for i=1:length(zeta) wd = sqrt(1-zeta(i).^2)*wn; x = exp(-zeta(i)*wn*t).*(((zeta(i)*wn*x0+v0)./wd)*sin(wd*t)+x0*cos(wd*t)); plot(t,x), grid hold on end xlabel('t(s)'), ylabel('x(t)') grid on legend('\zeta_1=0.05','\zeta_2=0.1','\zeta_1=0.2')

Problem 23: Figure shows a eletrcial sircuit with resistors and voltage sources. Write a MATLAB program to determine the current in each resistor using mesh current method based on Kirchoffs voltage law. Given V1 = 22 V, V2 = 12 V, V3 = 44 V, R1 = 20 , R2 = 12 , R3 = 15 , R4 = 7 , R5 = 16 , R7 = 10 , R8 = 15 .

R1 V1 I1 R2

R3 I3

I2 R5

R4

V2

R6 I4 R8

R7

V3

I 1 V1 I 0 R4 R7 2 = I 3 V2 + R 4 + R6 ) R6 ( R6 + R7 + R8 ) I 4 V3 R6 Create a resistance matrix and find values of I using matrix inversion or division method R3 0

Solution 23: Equations can be written as R2 ( R1 + R2 + R3 ) ( R2 + R4 + R5 + R7 ) R2 ( R3 R3 R4 0 R7 Problem 24:

Solve the first order linear differential equation

dx = x + t , with initial condition x(0) = 0. use ode dt

solver to compute solution Solution 24: Step1: write a equation as system of first order dx = x+t equations, dt Step2: write a function to compute the derivatives
function xdot=simpode(t,x); % SIMPODE computes xdot = x + t % Call syntax xdot = simpode(t,x) xdot = x + t;

Step 3: Use ode23 to compute the solution >> tspan=[0 2]; x0=0; >> [t x] =ode23('simpode',tspan,x0); >> plot(t,x) >> xlabel('t'),ylabel('x') Problem 25: Solve the equation of motion of a nonlinear pendulum d 2 d 2 + 2 sin( ) = 0 = 2 sin( ) with initial conditions (0) = 1, d/dt (0) = 0. dt 2 dt 2

Solution 25: Step 1 Wrtie equations in terms of first order equations


Z2 Let Z1 = and Z2 = d / dt, equation can be written in matrix form as, Z 1 = 2 Z 2 sin( ) Step 2 write a function to compute new state derivative
function zdot = pend(t,z); % Call syntax zdot = pend(t,z) % inputs are t = time % z = [z(1); z(2)] = [theta; thetadot] % output is : zdot = [z(2); w.^2sin(z(1))] wsq = 1.56; % specify a value of w^2; zdot = [z(2); -wsq.*sin(z(1))];

Note that z(1) and z(2) refer to the first and second order elements of vector z. Step 3 use ode23 or ode45 for solution
% tutorial 25 tspan=[0 50]; z0=[1;0]; % assign values of tspan [t z] =ode23('pend',tspan,z0); % run ode23 x = z(:,1);y=z(:,2); % x = 1st column of z, y = 2nd column figure(1) plot(t,x,t,y) % plot x and y xlabel('t'),ylabel('x and y') legend('Displacement','Velocity') figure(2) plot(x,y) % plot of phase potrait xlabel('Displacement'),ylabel('Velocity') title('Phase plane of nonlinear pendulum')

Step 4 Extract results and plot Problem 26:

Consider solving the following initial value problem:


Solution 26: Create the following .m file called ex1.m:

function xprime=ex1(t,x) xprime=sin(tx); Save it in the workspace. In the Matlab command window, type: > > [t,x] = ode45(ex1,[0 10], 1); >> plot(t,x);
Problem 27:

Solution 27: Create a .m file called ex2.m with the following content:

function yprime=ex2(t,y) yprime=[cos(y(2))+sin(t); sin(y(1))-cos(t)]; Now y and yprime are both column vectors. In the command window, type the following: >> tspan=[0, 10]; >> y0=[5.1, 6.7]; >> [t, y]=ode45(ex2, tspan, y0); >> plot(t, y); Of course, you can save the above commands to a .m file and type the name of the file in the command window to run it.
Problem 28:

Let

, the problem is written as:

Solution 28: Create the function ex3.m as follows:

In the command window, type: >> z0=[0;1]; >> tspan=[0 5]; >> [t,z]=ode45(ex3, tspan,z0); >> plot(t,z); We get this graph:
Problem 29 Using MATLAB find the solution of Ax = y 1 3 2 A= y= , 1 1 1 Solution 29: A = [ 3 2; 1 -1]; Y= [-1 ; 1]; X=A\Y X= 0.2000 -0.800

Problem 30: Calculate C = A + B, D = A B, E = AB Where, 1 2 3 4 1 2 A = 0 1 4 B = 3 2 1 3 0 2 0 1 2 Solution 30: Problem 30: Two material properties of carbon monoxide gas are given below T Beta Alpha 300 3.33e3 0.212e4 400 2.5e3 0.3605e4 500 2.00e3 0.5324e4 600 1.67e3 0.719e4

Where T is temperature in Kelvin, Beta is thermal expansion coefficient, and alpha is thermal diffisivity. Find by MATLAB the properties for T = 321 440, 571 respectively
Solution 30:
% Tutorial 30 clear all clc Temp=[300 400 500 600]; Beta=1000*[3.33 2.5 2.0 1.67]; Alpha=10000*[0.2128 0.3605 0.5324 0.7190]; Ti = [321 440 571 581]; Propty1 = interp1(Temp,Beta,Ti,'linear'); Propty2 = interp1(Temp,Alpha,Ti,'linear'); [Ti; Propty1; Propty2]

Problem 31: Suppose a functional relation y = y(x) given in a tabular form as Y 0 0.25 0.50 0.75 1.00 Y(x) 0.9162 0.8109 0.6931 0.5596 0.4055

Where y(x) is a monotonically increasing function of x, Find values of x that satisfies y = 0.9, 0.7, 0.6 and 0.5, respectively by MATLAB
% Tutorial 31 clear all clc x=[0 0.25 0.5 0.75 1.0];

y=[0.9162 0.8109 0.6931 0.5596 0.4055]; yi = [0.9 0.7 0.6 0.5]; xi = interp1(y,x,yi,'linear'); [yi; xi]

Problem 32: Desities of sodium for three temperatures are given as I 1 2 3 Temperature 94 205 371 Density 929 902 860

Write the Largrange interpolation formula that fits the three data points. Find density for T = 251 deg. C by Lagrange Interpolation Solution 32: % Tutorial 32 clear all clc x=[94 205 371]; y=[929 902 860]; xi = [251]; yi = lagrange(y,x,xi); [yi; xi] Problem 33: Matrix A is given by

3 4 2 A = 3 1 1 Find eigen values directly by eig, expand A into its characteristics polynomial, and 2 0 5
find the roots of the characteristics of equations Solution 33: % Tutorial 33 clear all clc A = [3 4 -2; 3 -1 1; 2 0 5]; A_eig = eig(A) A_poly = poly(A) A_roots = roots(A_poly) Output A_eig = -2.7503 4.8751 + 1.4314i 4.8751 - 1.4314i A_poly = 1.0000 -7.0000 -1.0000 71.0000

A_roots = 4.8751 + 1.4314i 4.8751 - 1.4314i -2.7503 Problem 34: A set of four data points is given by X = [ 1.1 2.3 3.9 5.1 ] Y = [ 3.887 4.276 4.651 2.117 ] Find the coeffificents of the interpolation polynomial fitted to the data set, determine value of y for x = 2.101 and plot the polynomial with data points
Problem 35 An automobile of mass M = 2000 kg is crusing at speed of 30 m/s. The engine is suddenly disengaged at t = 0 sec. Assume that equation of crusing after t = 0 sec is given by du 2000u = 8.1u 2 1200 dx Where u is velocity and x is the linear distance of the car measured from the location at t = 0. The left side is the force of acceleration, the first term on right side is aerodynamic resistance. And second term is rolling resistance. Calculate how far the car moves before the speed reduces to 15 m/s. Solution 35
30

2000udu 2000udu = dx integrating equation = dx = x where sign on 2 8.1u 1200 8.1u 2 + 1200 15 0 left side is changed for switching the limits of integration, by applying a trapezoidal rule, 16 x u fi 0.5( f1 + f16 ) where f is integrand function i =1 Programming Step 1 : Develop a trapezoidal function which evaluates integral function I = trapez_v(f, h); I = h*(sum(f) - (f(1)+f(length(f)))/2); Step 2 : Write a script file for calculation of distance as below, % Tutorial 35 clear all, clc, n_points = 16; i = 1:n_points; h = (30-15) / n_points; u = 15+(i-1)*h; f = 2000*u./(8.1*u.^2+1200); x = trapez_v(f,h) Rewrite equation as,
Problem 36 Knowing that the exact answer is I = 4.006994, analyze the effect of the number of intervals n on the errors of the trapezoidal rule applied to the following integral

I = 1 + exp( x)dx
0

Solutrion 36 Step 1 : Develop a trapezoidal function which evaluates integral

function I = trapez_v(f, h); I = h*(sum(f) - (f(1)+f(length(f)))/2); Step 2 Write a script file % Tutorial 36 clear all, clc, Iexact = 4.006994; a = 0; b = 2; fprintf('\n Extended Trapezoidal Rule \n'); fprintf('\n n I Error \n'); n = 1; for k=1:6 n = 2*n; h = (b-1)/n; i = 1:n+1; x = a + (i-1)*h; f = sqrt(1+exp(x)); I = trapez_v(f,h); nn(k)=n; I(k)=I; Error(k)=Iexact(1)-I(k); end out_data=[nn; I; Error;]' Problem 37 A spherical water reservior of radius 5 m is full to the top. Water is to be drained from the hole of radius b = 0.1 m at bottom, starting at t = 0 s. If there is no friction. How much time does it take to drain the water untill the water level reaches to 0.5m measured from bottom. ? Solve by simpsons rule
Solution 37

u2 where u is 2 the velocity , z is level of water measured from the spherical center, R is the radius of the tank, and g is gravity acceleration. Consider a change of water level dz during time interval dt. The volume of water in dz is x2dz, where x is the radius of circular water surface at elevation z. Flow continuity relation can be written as, uAdt = - x2dz , where A is the cross section of exit hole and is given by A = b2 Radius of water surface x is related to z by R2 = z2 +x2. Eliminating u, x, and A from previous equation R2 z 2 dt = 2 dz , Notice that the level of water at the top of the tank is z =R, while that at 0.5 m b 2g(z + R from bottom is z = 0.9R. Integrating from z = R to 0.9R, we get 0.9 R R2 z 2 t= 2 dz 2 g ( z + R) R b Velocity of water draining from hole is determined by the energy equation, g ( z + R) =
Matlab Implementation Step 1 Develop a function for simpsons rule

function I=Simps_v(f,h) n=length(f)-1; if n==1 fprintf('\nData has only one data point') return; end if n==2 I=h/3*(f(1)+4*f(2)+f(3)); return end if n==3 I=3/8*h*(f(1)+3*f(2)+3*f(3)+f(4)); return end I=0; if 2*floor(n/2)~=n I=3/8*h*(f(n-2)+3*f(n-1) ... +3*f(n)+f(n+1)); m=n-3; else m=n; end I = I+(h/3)*(f(1)+4*sum(f(2:2:m))+f(m+1)); if m>2 I = I + (h/3)*2*sum(f(3:2:m)); End Step 2 Write a script program as below % Tutorial 37 clear R=5; g=9.81; b=0.1; z1=-R*.90; z2=R; h=(z2-z1)/20; z=z1:h:z2; f=(R^2-z.^2)./(b^2*sqrt(2*g*(z+R))); I=Simps_v(f,h)/60/60
Problem 38 Motion of an electron in an uniform electromagnetic field is given by, dV m = eV + B + eE where V is the velocity vector, B is the magnetic field vector, E is the electric field dt vector, and m is mass of the electron, and e is the charge of electron. Initial condition V = (-10, 2, 0.1) X 105 m/s Initial Position of electron R = (0, 0, 0) m Magnetic Field Vector B = ( 0, 0, 0.1 ) T Electric Field Vector E = (0, 2, 0) X 104 V/m Mass of electron m =9.1 X 10-31 kg Charge of electron e = 1.6 X 10-19 c

Solve equation by Runge Kutta method with h = 0.5 X 10-11 s for 0 < t < 2 X 10-9 s, and determine the locus of the electron. Plot a trajectory of the electron in a three dimensional plane, and velocity components as functions of time as well as in the three dimensional phase space.
Solution 38 Step 1 Develop a function which carry out a vector product function c = vxv_(a,b) % c = [a] X [b] % a b c are vectors c=[a(2)*b(3)-a(3)*b(2); -a(1)*b(3)+a(3)*b(1); a(1)*b(2)-a(2)*b(1)]; Step 2 Write a scrip file as below % Tutorial 38 clear all clf, clc m =9.1e-31; e = 1.6e-19; B = [0; 0; 0.1]*e/m; E = [0; 2e4; 0]*e/m; h=0.5e-11; v(:,1)=1e5*[-10;2;0.1];

t(1)=0; xyz(:,1)=[0;0;0]; epm=e/m; for i=2:400 t(i)=h*i; k1=h*(vxv_(v(:,i-1),B)+E); k2=h*(vxv_(v(:,i-1)+k1,B)+E); v(:,i)=v(:,i-1)+0.5*(k1+k2); xyz(:,i)=xyz(:,i-1)+0.5*(v(:,i-1)+v(:,i))*h; end figure(1) plot3(xyz(1,:),xyz(2,:),xyz(3,:)) axis([-5 5 -1 2 0 3]*1e-4) xlabel('X');ylabel('Y');zlabel('Z'); figure(2) plot3(xyz(1,:),xyz(2,:),xyz(3,:)) xlabel('X');ylabel('Y');zlabel('Z'); view([0,0,1]) figure(3) plot3(v(1,:),v(2,:),v(3,:)) xlabel('V_x');ylabel('V_y');zlabel('V_y'); figure(4) plot(t,v(1,:),t,v(2,:),t,v(3,:)) xlabel('t');ylabel('Velocities'); legend('V_x','V_y','V_z')

Problem 39 Write a program for lobe of oscillating liquid jet % Tutorial 39 % plots a lobe of liquid jet clear, clf hold on dth=2*pi/40; th=0:dth:2*pi; r =ones(size(th)); colormap gray for n=1:51 b=n-1; x(n,:)=cos(th)*(1-0.25*cos(b*0.3)); y(n,:)=sin(th)*(1+0.25*cos(b*0.3)); z(n,:)=n*0.3*ones(size(th)); m=n+9; if floor(m/2)*2 ==m plot3(z(n,:),x(n,:),y(n,:)-5) end end hold off figure(2) surfl(z,x,y+2,[-10,60]) axis([0 13 -5 15 -10 5])

Control System MATLAB Tutorials


Problem 1 Find a poles of the follwing transfer functions and also compute step response characteristics of following systems 1 2 s 2 + 5s + 1 2 4s + 2 , T2 = 2 , T3 = 3 , T1 = 4 T1 = 2 2 s + 3s 2 + 3s + 1 s + 2s + 2 s + 2s + 2 s + 2 s 3 + 5s 2 + 2 s + 2 Solution 1:
% Control Syst tut 01 % Poles of tranfer functions and % computation of step responses for all TFs num1=[2]; den1=[1 2 2]; sys1=tf(num1,den1) P1 = pole(sys1);Z1 = zero(sys1); figure(1) subplot(2,2,1), step(sys1) num2=[4 2]; den2=[1 2 2]; sys2=tf(num2,den2) P2 = pole(sys2);Z2 = zero(sys2); subplot(2,2,2), step(sys2) num3=[1]; den3=[2 3 3 1]; sys3=tf(num3,den3) P3 = pole(sys3);Z3 = zero(sys3); subplot(2,2,3), step(sys3) num4=[2 5 1]; den4=[1 2 5 2 2]; sys4=tf(num4,den4) P4 = pole(sys4);Z4 = zero(sys4); subplot(2,2,4), step(sys4)

Problem 2: Find each of second order systems below find , n, Ts, Tp, Tr, % overshoot, and plot step response using MATLAB 130 0.045 10 3 T (s) = 2 , T ( s) = 2 , T ( s) = 2 s + 15s + 130 s + 0.025s + 0.045 s + 1.325 10 4 s + 10 8 Solution 2:
% Control tut 02 % % first tranfer function num1=[130]; den1=[1 15 130]; Ta1=tf(num1,den1) wn1=sqrt(den1(3)) zeta1=den1(2)/(2*wn1) Tsa1=4/(zeta1*wn1) Tpa1=pi/(wn1*sqrt(1-zeta1^2)) Tra1=(1.76*zeta1^30.417*zeta1^2+1.039*zeta1+1)/wn1 Per1=exp(-zeta1*pi/sqrt(1-zeta1^2))*100 figure(1) subplot(221), step(Ta1)

num2=[0.045]; den2=[1 0.025 0.045]; Ta2=tf(num2,den2) wn2=sqrt(den2(3)) zeta2=den2(2)/(2*wn2) Tsa2=4/(zeta2*wn2) Tpa2=pi/(wn2*sqrt(1-zeta2^2)) Tra2=(1.76*zeta2^3-0.417*zeta2^2+1.039*zeta2+1)/wn2 Per2=exp(-zeta2*pi/sqrt(1-zeta2^2))*100 figure(1) subplot(222), step(Ta2) num3=[10E8]; den3=[1 1.325E4 10E8]; Ta3=tf(num3,den3) wn3=sqrt(den3(3)) zeta3=den3(2)/(2*wn3) Tsa3=4/(zeta3*wn3) Tpa3=pi/(wn3*sqrt(1-zeta3^2)) Tra3=(1.76*zeta3^3-0.417*zeta3^2+1.039*zeta3+1)/wn3 Per3=exp(-zeta3*pi/sqrt(1-zeta3^2))*100 figure(1) subplot(223), step(Ta3)

Problem 3:

For a closed loop system defined by,

C (s) 1 , = 2 R( s ) s + 2s + 1 plot the unit step response curves for = 0.0, 0.1, 0.2, 0.4, 0.5, 0.6, 0.8, and 1.0. n is normalized to 1, plot a three dimensional coruve for step reponse as above

Solution 3:
% Control system tut 03 % 2D and 3D plots for unit step response zeta = [0 0.1 0.2 0.4 0.5 0.6 0.8 1.0]; t = 0:0.2:15; figure(1) for n = 1:8; num = [0 0 1]; den = [1 2*zeta(n) 1]; sys(n) = tf(num,den) step(sys(n),t); y(:,n) = step(sys(n),t); hold on end figure(2) mesh(t,zeta,y') xlabel('t sec'), ylabel('\zeta'), zlabel('Amplitude')

Problem 4: Write a equations of motion for the simple pendulum where all mass is concentrated at the endpoint. Use MATLAB to determine the time history of to step input of Tc of 1 N-m. Assume l =1 m, m = 0.5 kg, and g = 9.81 m/s2. Solution 4:

Equation of motion of pendulum is T g + = c 2 and transfer function is given l ml 1 2 ( s ) = ml by Tc ( s ) s 2 + g l Script Program % Control tut 04 t=0:0.02:10; m=0.5; g=9.81; l=1; tc =1; num=[1/m*l^2]; den=[1 0 g/l]; sys = tf(num,den); y =step(sys,t); plot(t,y) Problem 5 Solve following state space equation by SIMULINK

Problem 6 Consider the double integrator system G(s), which is open loop unstable. To stabilize this plant, we use a lead compensator, K(s). Prepare a simulink model for this s +1 2.5 simulate this model upto 100 seconds G(s) = 2 , K (s) = s + 10s + 1 s+5 Solution 6

Problem 7 The Lorenz system is set of three first order nonlinear differential equations as given below, Simulate using Simulink Modeling
x = a ( y x) y = x(b z ) y where a =10, b = 28, c = -2.67, and Initial conditions are x(0) =1, y(0)=1, and z(0)=1 z = cz + xy Solution 7

Problem 8 Simulate a Two degree freedom system given by following relations


M 1 x1 + (k1 + k2 ) x1 + (c1 + c2 ) x1 k2 x2 c2 x2 = 0 M 2 x2 + k2 x2 + c2 x2 c2 x1 k2 x1 = F sin(20t ) Where M1 =10kg, M2=20kg, k1 = 1000 N/m, k2=200 N/m, c1=c2=120 Ns/m, F = 100;

Solution

Problem 9 Simulate following Duffing System

x= y

x(0) = 5 y (0) = 5

y = ( x3 + x + y ) + cos

(0) = 3

Problem 10 Simulate following Rossler System of equations


x = y z x(0) = 5 1 y = x+ y y (0) = 5 5 1 z = + zx 5.7 z z (0) = 5 5 Problem 11 Simple pendulum nonlinear equation is given by following relation, determine a velocity and displacement plot with respect to time using SIMULINK and ode solver also
x1 = x2 x2 =

T g sin x1 + c 2 l ml

Solution 11

ODE solution global Wn2 Uo Wn2=9.82; Uo=5; t0=0; tf=10;

tspan=[t0,tf]; X0=[0 0]; [t,x]=ode23(@pendot,tspan,X0) function xdot=pendot(t,x) global Wn2 Uo if t <= 1 U=Uo; else U=0; end xdot(1)=x(2); xdot(2)=(-Wn2*sin(x(1))+U); Problem 12

You might also like