Intriduction - SAM
Intriduction - SAM
MATLAB
Introduction to MATLAB
2
What is MATrix LABoratory ?
It is developed by The Mathworks, Inc. (http://www.mathworks.com)
• To add a legend, either use the legend command or via insert in the Menu
Bar on the figure. Many other actions are available in Tools.
• Other frequently used utilities that are available in both forms are:
• save, load
Introduction to MATLAB
27
Surface Plot
>> Z = peaks; % generate data for plot; peaks returns function values
>> surf(Z) % surface plot of Z
b m a ih m
cos( x )dx
a
i 1
a ( i 1) h
cos( x )dx cos(a (i 12 )h )h
i 1
mid-point of increment
a b
X(1) = a + h/2 X(m) = b - h/2
Introduction to MATLAB
31
Integration Example — using vector form
% integration with vector form
tic
m = 100;
a = 0; % lower limit of integration
b = pi/2; % upper limit of integration
h = (b – a)/m; % increment length
x = a+h/2:h:b-h/2; % mid-point of m increments
integral = sum(cos(x))*h;
toc
a b
X(1) = a + h/2 X(m) = b - h/2
Introduction to MATLAB
32
Hands On Exercise
1. Use the editor to write a program to generate the figure that describe the
integration scheme we discussed. (Hint: use plot to plot the cosine curve.
Use bar to draw the rectangles that depict the integrated value for each
interval. Save as plotIntegral.m
2. Compute the integrals using 10 different increment sizes (h), for m=10, 20,
30, . . . , 100. Plot these 10 values to see how the solution converges to the
analytical value of 1.
Introduction to MATLAB
33
Hands On Exercise Solution
a = 0; b=pi/2; % lower and upper limits of integration
m = 8; % number of increments
h = (b-a)/m; % increment size
x= a+h/2:h:b-h/2; % m mid-points
bh = bar(x,cos(x),1,'c'); % make bar chart with the bars in cyan
hold % all plots will be superposed on same figure
x = a:h/10:b; % use more points at which to evaluate cosine
f = cos(x); % compute cosine at x
ph = plot(x,f,'r'); % plots x vs f, in red
% Compute integral with different values of m to study convergence
for i=1:10
n(i) = 10+(i-1)*10;
h = (b-a)/n(i);
x = a+h/2:h:b-h/2;
integral(i) = sum(cos(x)*h);
end
figure % create a new figure
plot(n, integral)