You are on page 1of 33

Applied Numerical Methods

with MATLAB®
for Engineers and Scientists
4th Edition
Steven C. Chapra

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and


Prof. Steve Chapra, Tufts University

©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

Programming with MATLAB

©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

will produce x values of 24, 19, 14, 9, 4, and -1,


then stop.
©McGraw-Hill Education.
Example
The (x, y) coordinates of a projectile can be
generated as a function of time, t, with the
following parametric equations
x = v0 cos(θ0 t)
y = v0 sin(θ0 t) − 0.5 gt2

where v0 = initial velocity (m/s)


θ0 = initial angle (radians)
g = gravitational constant (= 9.81 m/s2)
©McGraw-Hill Education.
Script
The following code illustrates both approaches:
clc,clf,clear
g=9.81; theta0=45*pi/180; v0=5;
t(1)=0;x=0;y=0;
plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)
axis([0 3 0 0.8])
M(1)=getframe;
dt=1/128;
for j = 2:1000
t(j)=t(j-1)+dt;
x=v0*cos(theta0)*t(j);
y=v0*sin(theta0)*t(j)-0.5*g*t(j)^2;
plot(x,y,'o','MarkerFaceColor','b','MarkerSize',8)
axis([0 3 0 0.8])
M(j)=getframe;
if y<=0, break, end
end
pause
movie(M,1)
©McGraw-Hill Education.
Result

©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.

For clarity of reading, the statements of a


structure are generally indented to show
which lines of controlled are under the
control of which structure.

©McGraw-Hill Education.
Anonymous Functions

• Use an anonymous function (multiple input/


single output function in a single expression)
when a function is used numerous times.
– Define the function form of the anonymous
function, e.g., f=@(x) exp(x)
– Wherever the function is used simply use f(x)
– Can use multiple inputs f=@(x,y) y*exp(x)
Ex. of an Anonymous Function

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

• In order to enable x, y and a as symbolic


variable use the command:
syms x y a
Example for Function factor

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

creates the symbolic variables s and r. The terms


s = x + y and r = sqrt(x^2 + y^2) are
examples of symbolic expressions.

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’

diamond: ‘d’ yellow: ‘y’

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

• In the case of the custom plot used here, 5


lines of code were required to customize the
plot.
• You can use consistent sets of customized
plotting code to standardize your plots for a
report or presentation.
Using Figure Properties

• When you want to add other special features


to your plots, you can use the options
provided under figure properties.
• In the figure window, select Figure
Properties and then click on the More
Properties box.
3-D Plots
• 3-D line plots
• Mesh and surface plots
• Contour plots
3-D Line Plots

• Plotting 3-D spatial location as a function of


time.

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.

The optional form ezplot(E,[xmin xmax])


generates a plot over the range from xmin to xmax.

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

You might also like