Professional Documents
Culture Documents
Lecture 4 - ch3 - Programming
Lecture 4 - ch3 - Programming
with MATLAB®
for Engineers and Scientists
4th Edition
Steven C. Chapra
©McGraw-Hill Education. All rights reserved. Authorized only for instructor use in the classroom. No reproduction or further distribution permitted without the prior written consent of McGraw-Hill Education.
Chapter 3
©McGraw-Hill Education. All rights reserved. Authorized only for instructor use in the classroom. No reproduction or further distribution permitted without the prior written consent of McGraw-Hill Education.
Vectorization
Sometimes, it is more efficient to have
MATLAB perform calculations on an entire
array rather than processing an array element
by element. This can be done through
vectorization.
for loop Vectorization
i = 0; t = 0:0.02:50;
for t = 0:0.02:50 y = cos(t);
i = i + 1;
y(i) = cos(t);
end
©McGraw-Hill Education.
while Loops
A while loop is fundamentally different from a for loop
since while loops can run an indeterminate number of
times. The general syntax is
while condition
statements
end
where the condition is a logical expression. If the
condition is true, the statements will run and
when that is finished, the loop will again check on the
condition.
Note - though the condition may become false as
the statements are running, the only time it matters
is after all the statements have run.
©McGraw-Hill Education.
Code Example
clc;clear all;
n=0;
while n<=1
n = input(' Enter a number: ‘); Enter a number: 1
m=n; Enter a number: 0
if n>1 Enter a number: 5
f=n ; 5! = 120
end >>
end
while n > 1
n = n-1;
f = f*n;
end
disp([num2str(m) ‘! = ' num2str(f)])
©McGraw-Hill Education.
Early Termination
Sometimes it will be useful to break out of a for or
while loop early - this can be done using a break
statement, generally in conjunction with an if
structure.
Example:
•
x = 24
while (1)
x = x - 5
if x < 0, break, end
end
©McGraw-Hill Education.
Nesting and Indentation
Structures can be placed within other
structures. For example, the statements
portion of a for loop can be comprised of
an if...elseif...else structure.
©McGraw-Hill Education.
Anonymous Functions
Cylinder: Vol=πr2H
function cylinder
clear; clc;
Vol=@(r,H) pi*r^2*H
V1=Vol(2,4)
V2=Vol(4,2)
end
Enabling Symbolic Variables
>> syms x;
>> E=x^2-5*x+6;
>> factor(E)
ans =
(x - 2)*(x - 3)
You can use symbolic variables in expressions
and as arguments of functions. You
use the operators + - * / ^ and the built-in
functions just as you use them with numerical
calculations. For example, typing
>>syms x y
>>s = x + y;
>>r = sqrt(x^2 + y^2);
10-7
Expression Manipulation
• Simplify an expression E
simplify(E)
• Factor an expression E
factor(E)
• Expand an expression E
expand(E)
Example: syms x y ;
expand(sin(x+y))
If you want to tell MATLAB that f is a function of the
variable t, type :
syms t f(t)
f(t)=t^3+4
f(2)
f(t+2)
pretty(f(t)-f(t-2))
10-14
Typical Plot
Comparison of Function and Data
4 function x2
data
f(x)
2
← Additional text
0
0 0.5 1 1.5 2
x
Plot Features
• Title
• Labels for x- and y-axes
• Legend for two or more curves
• Proper size for numerical values along x-
and y-axes
• A smooth curve for function that is plotted
with the proper weight
• A text box containing additional
information about the plot.
Ways to Generate Custom Plots
• Custom Commands
• Using Figure Properties
• Standardized Format Program
Custom Commands
Function MATLAB Statement
Title title(‘title string’,’FontSize’,24)
Label for x- xlabel(‘x label string’,’FontSize’,20)
axis
Label for y- ylabel(‘y label string’,’FontSize’,20)
axis
Values on Axes(‘XTick’,[0 1 2],’YTick’,[0 1
axes 2],’FontSize’,20)
Legend legend(‘string_1’,’string_2’,string_3)
Text text(x,y,‘text string’,’FontSize’,20)
Adds/remove grid on/grid off
grid lines
Using Symbols for Titles and
Labels
• Lower case Greek symbols: ‘\alpha’ for
α; ‘\tau’ for τ and ‘\theta’ for θ
• Upper case Greek symbols: ‘\Delta’ for
∆; ‘Omega’ for Ω
• For an itallic letter: ‘\itx’ for x
Plotting Lines and Symbols
Lines Symbols Color
solid: ‘-’ plus: ‘+’ black: ‘k’
dashed: ‘--’ circle: ‘o’ red: ‘r’
dotted: ‘.’ asterisk: ‘*’ blue: ‘b’
dot-dash: ‘.-’ point: ‘.’ green: ‘g’
cross: ‘x’ cyan: ‘c’
white: ‘w’
Program used for Custom Plot
function Fig8_3
clear; clc; clear all;
x=[0:.01:3];
y=3*exp(-x).*sin(pi.*x);
axes('XTick',[0 1 2 3],'YTick',[-.5 0 .5
1],'FontSize',20)
plot(x,y,'k-','LineWidth',2)
title('Custom Plot','FontSize',24)
xlabel('\itx','FontSize',20)
ylabel('3\ite^-^x
sin\pi\itx','FontSize',20)
end
Custom Plot
Custom Plot
4
3
3e-x sinπx
-1
-2
0 0.5 1 1.5 2 2.5 3
x
Custom Commands
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t);
Mesh and Surface Plots
• Used to plot a function that has two
independent variables, e.g., f(x,y).
• Mesh plot depicts the surface in 3-D.
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2);
Z = sin(R)./R;
mesh(X,Y,Z)
Example of 3-D Mesh Plot
150
100
50
-50
10
5 10
0 5
0
-5
-5
-10 -10
The MATLAB function ezplot(E) generates a plot of
a symbolic expression E, which is a function of one
variable. The default range of the independent variable
is the interval [−2π, 2π] unless this interval contains a
singularity.
10-16
Plot of the function f(x) = x 2 − 6x + 7 generated by the
ezplot.
syms x f(x)
f(x)=x^2-6*x+7
ezplot(f(x),[-2 6])
10-17