COMPUTATIONAL LAB (ME-106) INTRODUCTION TO MATLAB By K.Kiran Kumar Assistant professor Mechanical Engineering Department B.S.Abdur Rahman University Email:-
[email protected] Ph.no:- 9047475841
WHAT IS MATLAB? MATLAB (MATrix LABoratory) is basically a high level language which has many specialized toolboxes for making things easier for us.
MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It‟s name is derived from MATrix LABoratory. MATLAB has since been expanded and now has bui lt-in functions for solving problems requiring data analysis, signal processing, optimization, and several other types of scientific computations. It also contains functions for 2-D and 3-D graphics and anim ation.
Powerful, extensible, highly integrated computation, programming, visualization, and simulation package.
Widely used in engineering, mathematics, and science. Why?
FEATURES
o
MATLAB is an interactive system for doing numerical computations. MATLAB makes use of highly respected algorithms and hence you can be confident about your results. Powerful operations can be performed using just one or two commands. You can also build your own set of functions. Excellent graphics facilities are included.
MATLAB TOOLBOXES Signal & Image Processing Math and Analysis Optimization Signal Processing Requirements Management Interface Image Processing Statistics Communications Neural Network Frequency Domain Identification Symbolic/Extended Math Higher-Order Spectral Analysis Partial Differential Equations System Identification
PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object
Wavelet Filter Design Control Design Control System Fuzzy Logic Robust Control μ-Analysis and Synthesis Model Predictive Control
SIMULINK
A simulation tool for dynamic systems Input
Output System
Simulink library Browser:
Collection of sources, system modules, sinks
WHAT ARE WE INTERESTED IN ?
MATLAB is too broad tool used in industry and Research for real time interfacing of sensors and machine vision etc. and programming the real time systems for active control of the system behavior. For our course purpose in this Laboratory we will have brief overview of basics and learn what can be done with MATLAB at beginner level.
WHY DO WE EED TO N PERFORM ANALYSIS IN MATLAB ???
AREAS WHERE MECHANICAL ENGINEERS USE MATLAB
Solving kinematics, kinetics and complete dynamic systems control of Automotive suspension , Thermal systems etc.,
AERO PLANE SUSPENSION OF LANDING GEAR M
M
Mg
Fs Fc
Yo
2
Ys
Yin
M
d yo dt
2
Mg
Fc
Fs
BASICS Displacement distance 35 Metres
Speed 65 m/s
D Time
Velocity V Time
0-60 m/s in 8.6 second
Acceleration A Time
UNDAMPED FREE VIBRATION Displacement
d = D sinnt
Displacement
D Time
T
1 T
m
Frequency
Period, Tn in [sec] k
Frequency, fn=
1 Tn
= 2 fn =
k m
n
in [Hz =
1/sec]
CONTINUED… Natural frequency of a simple single degree of freedom undamped system is given by the equation ωN = square root of (stiffness / mass) Usually we do not want structures to vibrate in resonance
COMPONENTS OF A CAR For comfortable ride in a car requires analysis of car frame and many other components, e.g. exhaust systems (bellows), shock absorber, tire etc. Let us look into a shock absorber in more detail
We know what a typical shock absorber does saves us from unpleasant vibration.
Let us look at a quarter bus/truck/car model xs
ms ks
cs mu kt
xu u
u = road profile input ks = suspension spring constant kt = tire spring constant cs = suspension damping constant mu = unsprung mass ms = sprung mass xu = displacement of unsprung mass xs = displacement of sprung mass
FOUR WHEELER SUSPENSION SYSTEM
Consider the following suspension system.
Solve for y given yin
1 5
M
Mg
y Suspension system
ys
yin
SUSPENSION SYSTEM IN FOUR WHEELER
CONTINUED…
CONTINUED…
CONTINUED…
CONVENTIONAL PASSIVE SUSPENSION
zs
sprung mass (body) Ms
suspensionspring unsprung mass (wheel, axle) Mu tyre stiffness Kt
suspensiondamper zu
zr
MATLAB MODEL FOR BUS
SUSPENSION
Designing an automatic suspension system for a bus
MATLAB SCREEN
VARIABLES
No need for types. i.e.,
int a; double b; float c; Accuracy and comfort is very high with matlab codes. >>x=5; >>x1=2;
ARRAY, MATRIX
LONG ARRAY, MATRIX
GENERATING VECTORS FROM FUNCTIONS
MATRIX INDEX
OPERATORS (ARITHMETIC)
MATRICES OPERATIONS
THE “DOT OPERATOR” By default and whenever possible MATLAB will perform true matrix operations (+ - *). The operands in every arithmetic expression are considered to be matrices. If, on the other hand, the user wants the scalar version of an operation a “dot” must be put in front of the operator, e.g., .*. Matrices can still be the operands but the mathematical calculations will be performed element-byelement. A comparison of matrix multiplication and scalar multiplication is shown on the next slide.
OPERATORS (ELEMENT BY ELEMENT)
DOT OPERATOR EXAMPLE >> A = [1 5 6; 11 9 8; 2 34 78] A = 1
5
6
11
9
8
2
34
78
>> B = [16 4 23; 8 123 86; 67 259 5] B = 16
4
23
8
123
86
67
259
5
DOT OPERATOR EXAMPLE (CONT.) >> C = A * B
% “normal” matrix multiply
C = 458
2173
483
784
3223
1067
5530
24392
3360
>> CDOT = A .* B
% element-by-element
CDOT = 16
20
138
88
1107
688
134
8806
390
THE USE OF “.” -OPERATION
MATLAB FUNCTIONS
COMMON MATH FUNCTIONS
BUILT-IN FUNCTIONS FOR HANDLING ARRAYS
MATLAB BUILT-IN ARRAY FUNCTIONS
Standard Arrays » eye(2)
Other such arrays:
ans = 1 0
ones(n), ones(r, c) 0 1
zeros(n), zeros(r, c) rand(n), rand(r,c)
» eye(2,3) ans =
1 0 »
0 1
0 0
RANDOM NUMBERS GENERATION
COMPLEX NUMBERS HANDLING FUNCTIONS
MATRIXES AND VECTORS
x = [1,2,3] , vector-row,
y=[1;2;3], vector-column,
x=0:0.1:0.8 , vector x=[0,0.1,0.2,0.3....0.8],
A = [1,3,5;5,6,7;8,9,10], matrix, A(1,2), element of matrix, 1. row, 2. column,
A(:,2), second column of matrix,
A(1,:), first row of matrix ,
C=[A;[10,20,30]] matrix with additional row,
B=A(2:3,1:2), part of matrix,
x‟, transpose. 42
MATRIXES AND VECTORS size(A), matrix size, det(A), determinant, inv(A), inverse matrix, eye(3), unit matrix, zeros(3,4), matrix of zeros,
rand(3,5), matrix of random values, sum(A), sum of elements, A*x, matrix-vector product (if dimensions are corresponding), A.*B, element multiplication of two matrixes. help sqrt, looking for known command, help, help topics are shown,
43
INTRODUCTION TO M-FILES PROGRAMMING Type-2 Programming
Type-1 programming
Program:clc;
Program:clc; clear all;
clear all;
p=input('enter the value of p:');
p=10,000; t=2;
t=input('enter the value of t:'); r=input('enter the value of r:');
r=11;
Solution:-
I=(p*t*r)/100;
I=(p*t*r)/100
Input: enter the value of p:10000
Solution:-
enter the value of t:2
I = 2200
enter the value of r:11
Output: I = 2200
GRAPHICS AND DATA DISPLAY
2-D plotting functions >> plot(x,y)
% linear Cartesian
>> semilogx(x,y) % logarithmic abscissa • uses base 10 (10n for axis units) >> semilogy(x,y) % logarithmic ordinate • uses base 10 (10n for axis units) >> loglog(x, y)
% log scale both dimensions
• uses base 10 (10n for axis units)
>> polar( theta,rho) % angular and radial
CONTINUED..
2-D display variants
Cartesian coordinates >> bar(x,y) >> barh(x,y) >> stem(x,y) >> area(x,y) >> hist(y,N)
% vertical bar graph % horizontal bar graph % stem plot % color fill from horizontal axis to line % histogram with N bins (default N = 10)
Polar coordinates >> pie(y) >> rose( theta,N) % angle histogram, N bins (default 10)
GRAPHICS AND DATA DISPLAY
3-D Plotting syntax
Line >> plotfunction(vector1, vector2, vector3) Vector lengths must be the same ►
Example >> a = 1:0.1:30; >> plot3( sin(a), cos(a), log(a) )
Pie >> pie3(vector) One dimensional data, but 3-D pie perspective
GRAPHICS AND DATA DISPLAY
3-D surface plotting functions >> contour(x,y,Z) % projection into X-Y plane >> surf(x,y,Z)
% polygon surface rendering
>> mesh(x,y,Z)
% wire mesh connecting vertices
>> waterfall(x,y,Z) • like mesh but without column connection lines • used for column-oriented data
BASIC TASK: PLOT THE FUNCTION SIN(X) BETWEEN 0≤X≤4Π
PLOT THE FUNCTION BETWEEN 0≤X≤4Π
PLOT THE FUNCTION e-X/3SIN(X) BETWEEN 0≤X≤4Π
DISPLAY FACILITIES
CONTD..
LINE SPECIFIERS IN THE plot() COMMAND
plot(x,y,‘line specifiers’)
L i ne Style
Specifier
Solid dotted : dashed dash-dot
--.
L i ne C ol o r red green blue Cyan magenta yellow black
Specifier
r g b c m y k
Marker Specifier T y pe plus sign + circle o asterisk * point . square s diamond d
Plots » x = 1:2:50; » y = x.^2; » plot(x,y)
2500
2000
1500
1000
500
0 0
5
10
15
20
25
30
35
40
45
50
Plots » plot(x,y,'*-') » xlabel('Values of x') » ylabel('y') 2500
2000
1500
y
1000
500
0 0
5
10
15
20
25
30
Values of x
35
40
45
50
MULTIPLE GRAPHS t=0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2);
1 0.8
plot(t,y1,t,y2); grid on
0.6 0.4 0.2
0 -0.2 -0.4 -0.6 -0.8
-1 01234567
MULTIPLE PLOTS t=0:pi/100:2*pi; y1=sin(t); y2=sin(t+pi/2); subplot(2,2,1) plot(t,y1) grid on subplot(2,2,2) plot(t,y2); grid on
subplot(i,j,k) • i is the number of rows of subplots in the plot • j is the number of columns of subplots in the plot • k is the position of the plot
INTERESTING FEATURE OF GENERATING SINE CURVE
x = 0:0.05:6;
y = sin(pi*x);
Y = (y >= 0).*y;
1 0.8 0.6 0.4 0.2
plot(x,y,':',x,Y,'-')
0 -0.2 -0.4 -0.6 -0.8
-1 0123456
CONTINUED..
x = 0:0.05:6;
y = sin(pi*x);
Y = (y >= 0).*y;
1 0.8 0.6 0.4 0.2
plot(x,y,„.',x,Y,'-')
0 -0.2 -0.4 -0.6 -0.8 -1 0123456
OPERATORS (RELATIONAL, LOGICAL)
POLYNOMIALS
MATLAB FUNCTIONS FOR POLYNOMIALS
Contd.. Representing Polynomials: x4 - 12x3 + 25x + 116 » P = [1 -12 0 25 116]; » roots(P) ans = 11.7473 2.7028 -1.2251 + 1.4672i -1.2251 - 1.4672i
» r = ans; » PP = poly(r) PP = 1.0000 -12.0000 -0.0000 25.0000 116.0000
Polynom ial Multiplication a = x3 + 2x2 + 3x + 4 b = 4x2 + 9x + 16 » a = [1 2 3 4]; » b = [4 9 16]; » c = conv(a,b)
c= 4
17
46
75
84
64
Evaluation of a Polynomial a = x3 + 2x2 + 3x + 4 » polyval(a, 2) ans =
26
Symbolic Math » syms x » int('x^3') ans = 1/4*x^4 » eval(int('x^3',0,2)) ans =
4 »
Solving Nonlinear Equations nle.m Function of the program:function f = nle(x) f(1) = x(1) - 4*x(1)*x(1) - x(1)*x(2); f(2) = 2*x(2) - x(2)*x(2) + 3*x(1)*x(2);
Program:-
x0 = [1 1]'; x = fsolve('nle', x0) Solution:x= 0.2500 0.0000
TO FIND EIGEN VALUES AND EIGEN VECTORS OF MATRICES
CONTINUED…
SOLVING LINEAR EQUATIONS
(TRY MANUALLY)
Solve manually and tell me what is the answer..?
That is find out x= y= z=
SOLVING SET OF
SIMULTANEOUS EQUATIONS
DIFFERENTATION
SOLVING DIFFERENTIAL EQUATIONS
PERFORMING INTEGRATION
NUMERICAL INTEGRATION
Numerical integration of the integral f (x) dx is called quadrature. MATLAB provides the following built-in functions for numerical integration:
quad:
It integrates the specified function over specified limits, based on adaptive Simpson's rule.
The general call syntax for both quad and quadl is as follows: Syntax:integral = quad(„function‟, a, b) dblquad: (It calculates double integration)
MATLAB provides a function dblquad. The calling syntax for dblquad is:
Syntax:I = dblquad(„function_xy‟, xmin, xmax, ymin, ymax)
FLOW CONTROL
CONTROL STRUCTURES
CONTROL STRUCTURES
CONTROL STRUCTURES
IF STATEMENT (EXAMPLE)
n = input(„Enter the upper limit: „);
if n < 1 disp („Your answer is meaningless!‟)
end
x = 1:n;
term = sqrt(x);
y = sum(term)
Jump to here if TRUE
Jump to here if FALSE
EXAMPLE PROGRAM TO EXPLAIN IF LOOP % Program to find whether roots are imaginary or not% clc; clear all; a=input('enter value of a:'); b=input('enter value of b:'); c=input('enter value of c:'); discr = b*b - 4*a*c; if discr < 0 disp('Warning: discriminant is negative, roots are imaginary'); end Solution:Input: enter value of a:1 enter value of b:2 enter value of c:3 Output: Warning: discriminant is negative, roots are imaginary
EXAMPLE OF IF ELSE STATEMENT Program:A = 2; B = 3; if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') end Solution:ans = B is bigger
IF STATEMENT EXAMPLE Here are some examples based on the familiar quadratic formula. 1. discr = b*b - 4*a*c; if discr < 0 disp('Warning: discriminant is negative, roots are imaginary'); end 2. discr = b*b - 4*a*c; if discr < 0 disp('Warning: discriminant is negative, roots are imaginary'); else disp('Roots are real, but may be repeated') end 3. discr = b*b - 4*a*c; if discr < 0 disp('Warning: discriminant is negative, roots are imaginary'); elseif discr == 0 disp('Discriminant is zero, roots are repeated') else disp('Roots are real') end
EXAMPLE OF FOR LOOP Problem: Draw graphs of sin(nπ x) on the interval −1 ≤ x ≤ 1 for n = 1,2,....,8.We could do this by giving 8 separate plot commands but it is much easier to use a loop.
Program:x=-1:0.05:1; for n=1:8 subplot(4,2,n); plot(x, sin(n*pi*x)); end
EXAMPLE OF FOR & WHILE LOOP 1.) % example of for loop% Program:for ii=1:5 x=ii*ii End Solution: 1 4 9 16 25 2.) %example of while loop% Program:x=1 while x