6 MatLab Tutorial Problems

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’)

Transcript of 6 MatLab Tutorial Problems

Page 1: 6 MatLab Tutorial Problems

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’)

Page 2: 6 MatLab Tutorial Problems

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.

Hint: 3259

+= CF

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

Page 3: 6 MatLab Tutorial Problems

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,

⎥⎦

⎤⎢⎣

⎡ −=⎥

⎤⎢⎣

⎡=⎥

⎤⎢⎣

⎡=

3555

4321

9362

CBA

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 % Enter matrices A, B, C A = [2 6; 3 9]; B = [1 2; 3 4]; C = [-5 5; 5 3]; D = A + B + C E = A*B*C F = C*B*A

Page 4: 6 MatLab Tutorial Problems

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

⎥⎥⎥⎥⎥⎥⎥⎥

⎢⎢⎢⎢⎢⎢⎢⎢

=

350000550000004300002100000093000062

G

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:

Taking log of both sides, we have TtPP −= )0ln()ln( or 01

^ataP +=

Where )0ln(0,/11),ln(^

PaandTaPP =−==

Page 5: 6 MatLab Tutorial Problems

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,

23321433

132

=++=++=++

zyxzyx

zyx

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

200 lb

V M C

300 lb

200 lb

25 inch

Page 6: 6 MatLab Tutorial Problems

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)')

Page 7: 6 MatLab Tutorial Problems

Problem 16: The acceleration due to gravity due to earth at any height h above the surface of the earth is given by,

22 /

)(sm

hRGMg+

−=

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, )cos(1 ϑε−

=Pr

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')

Page 8: 6 MatLab Tutorial Problems

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

22)/(1

/fm

nf

mm mrP

KPx ω

ωω=

−=

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.

Solution 19:

Equation of motion of vehicle is )sin()sin(22

2

tptmkxdtdxc

dtxdm mm ωωδω ==++

Amplitude ratio is given by, 222

2

)]/)(/(2[])/(1[

)/(

ncn

n

m

m

cc

u

ωωωω

ωωδ +−

=

Where, lvmKn πωω 2/ ==

l

K C

mW

K(x-δ- δst) C(x’-δ’)

x Equilibrium

Page 9: 6 MatLab Tutorial Problems

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

⎥⎥⎥⎥

⎢⎢⎢⎢

⎡−−

=

⎥⎥⎥⎥

⎢⎢⎢⎢

−−

=

6014112342127531

4321621745211203

BA

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

Solution 21:

Magnitude of frequency response is given by 2/1222 2)(1(

1)(

⎥⎥⎦

⎢⎢⎣

⎡⎟⎟⎠

⎞⎜⎜⎝

⎛+⎥

⎤⎢⎣

⎡−

=

nn

jG

ωωξ

ωω

ω

K C y(t)

x(t)

Page 10: 6 MatLab Tutorial Problems

Phase Response

⎥⎥⎥⎥⎥

⎢⎢⎢⎢⎢

⎟⎟⎠

⎞⎜⎜⎝

⎛+⎟⎟

⎞⎜⎜⎝

⎛−

⎟⎟⎠

⎞⎜⎜⎝

= −22

2

1

21

2tan)(

nn

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, )cos()( φωξω −= − tCetx d

tn

Where ndd

n

d

n

xvxvx

xC ωξωω

ξωφ

ωξω 2

0

0012

0020 1tan −=⎟⎟

⎞⎜⎜⎝

⎛ +=⎟⎟

⎞⎜⎜⎝

⎛ ++ −

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 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')

Page 11: 6 MatLab Tutorial Problems

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 Kirchoff’s 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 Ω.

Solution 23: Equations can be written as

⎥⎥⎥⎥

⎢⎢⎢⎢

=

⎥⎥⎥⎥

⎢⎢⎢⎢

⎥⎥⎥⎥

⎢⎢⎢⎢

++−++−

+++−++−

3

2

1

4

3

2

1

87667

664343

7475422

32321

0

)(0)(

)(0)(

VV

V

IIII

RRRRRRRRRRRRRRRRRR

RRRRR

Create a resistance matrix and find values of I using matrix inversion or division method Problem 24:

Solve the first order linear differential equation txdtdx

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

solver to compute solution Solution 24: Step1: write a equation as system of first order

equations, txdtdx

+=

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

)sin(0)sin( 22

22

2

2

θωθθωθ−=⇒=+

dtd

dtd with initial conditions θ(0) = 1, dθ/dt (0) = 0.

R5

V1

R1

I1 R2 R3

R4

R7

R6

R8

V3

V2 I2

I3

I4

Page 12: 6 MatLab Tutorial Problems

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

Let Z1 = θ and Z2 = dθ / dt, equation can be written in matrix form as, ⎭⎬⎫

⎩⎨⎧−

=⎪⎭

⎪⎬⎫

⎪⎩

⎪⎨⎧

)sin(22

2

1

θωZ

ZZ

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:

Page 13: 6 MatLab Tutorial Problems

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

⎥⎦

⎤⎢⎣

⎡−=⎥

⎤⎢⎣

⎡−

=11

,11

23yA

Solution 29: A = [ 3 2; 1 -1]; Y= [-1 ; 1]; X = A \ Y X = 0.2000 -0.800

Page 14: 6 MatLab Tutorial Problems

Problem 30: Calculate C = A + B, D = A – B, E = AB Where,

⎥⎥⎥

⎢⎢⎢

⎡=

⎥⎥⎥

⎢⎢⎢

⎡=

210123214

203410321

BA

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 Y(x) 0 0.9162 0.25 0.8109 0.50 0.6931 0.75 0.5596 1.00 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];

Page 15: 6 MatLab Tutorial Problems

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 Temperature Density 1 94 929 2 205 902 3 371 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 23 1 12 0 5

A−⎡ ⎤

⎢ ⎥= −⎢ ⎥⎢ ⎥⎣ ⎦

Find eigen values directly by eig, expand A into its characteristics polynomial, and

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

Page 16: 6 MatLab Tutorial Problems

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

22000 8.1 1200duu udx

= − −

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

Rewrite equation as, 2

20008.1 1200

udu dxu

=− −

integrating equation 30

215 0

20008.1 1200

xudu dx xu

= =+∫ ∫ where sign on

left side is changed for switching the limits of integration, by applying a trapezoidal rule, 16

1 161

0.5( )ii

x u f f f=

⎡ ⎤≈ Δ − +⎢ ⎥⎣ ⎦∑ where f is integrand function

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) 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

2

0

1 exp( )I x dx= +∫

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

Page 17: 6 MatLab Tutorial Problems

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

Velocity of water draining from hole is determined by the energy equation, 2

( )2ug z R+ = where u is

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

2 2

2 2 (R zdt dz

b g z R−

=+

, Notice that the level of water at the top of the tank is z =R, while that at 0.5 m

from bottom is z = 0.9R. Integrating from z = R to 0.9R, we get 0.9 2 2

2 2 ( )

R

R

R zt dzb g z R

−=

+∫

Matlab Implementation Step 1 Develop a function for simpson’s rule

Page 18: 6 MatLab Tutorial Problems

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,

dVm eV B eEdt

= + + where V is the velocity vector, B is the magnetic field vector, E is the electric field

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

Page 19: 6 MatLab Tutorial Problems

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')

Page 20: 6 MatLab Tutorial Problems

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])

Page 21: 6 MatLab Tutorial Problems

Control System MATLAB Tutorials

Problem 1 Find a poles of the follwing transfer functions and also compute step response characteristics of following systems

2252152,

13321,

2224,

222

234

2

12332221 ++++++

=+++

=++

+=

++=

ssssssT

sssT

sssT

ssT

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

842

3

22 1010325.110)(,

045.0025.0045.0)(,

13015130)(

+×+=

++=

++=

sssT

sssT

sssT

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^3-0.417*zeta1^2+1.039*zeta1+1)/wn1 Per1=exp(-zeta1*pi/sqrt(1-zeta1^2))*100 figure(1) subplot(221), step(Ta1)

Page 22: 6 MatLab Tutorial Problems

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, 12

1)()(

2 ++=

sssRsC

ξ,

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:

Page 23: 6 MatLab Tutorial Problems

Equation of motion of pendulum is

2cTg

l mlθ θ••

+ = and transfer function is given

by 2

2

1( )( )c

s mlgT s sl

Θ=

+

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

2

2.5 1( ) , ( )10 1 5

sG s K ss s s

+= =

+ + + simulate this model upto 100 seconds

Solution 6

Page 24: 6 MatLab Tutorial Problems

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

z cz xy

= −

= − −

= +

where a =10, b = 28, c = -2.67, and Initial conditions are x(0) =1, y(0)=1, and z(0)=1

Solution 7

Page 25: 6 MatLab Tutorial Problems

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

1 1 1 2 1 1 2 1 2 2 2 2

2 2 2 2 2 2 2 1 2 1

( ) ( ) 0

sin(20 )

M x k k x c c x k x c x

M x k x c x c x k x F t

•• • •

•• • •

+ + + + − − =

+ + − − =

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

Page 26: 6 MatLab Tutorial Problems

3

(0) 5

( ) cos (0) 5

(0) 3

x y x

y x x y yθ

θ ω θ

= =

= − + + + =

= =

Problem 10 Simulate following Rossler System of equations

(0) 51 (0) 55

1 5.7 (0) 55

x y z x

y x y y

z zx z z

= − − =

= + =

= + − =

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

1 2

2 1 2sin c

x xTgx x

l ml

=

= − +

Solution 11

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

Page 27: 6 MatLab Tutorial Problems

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