Summary: This is an example of using for loops in m-files to solve a simple engineering modeling problem.
Suppose you have a cylinder of height
A lower bound for this problem is found as follows:
You are given the following values:
The following shows the commands typed at the >> prompt and the output produced:
>> d = 1.54
d =
1.5400
>> b = 8
b =
8
>> h = 14
h =
14
>> vcyl = h*pi*(b/2)^2
vcyl =
703.7168
>> vcube = d^3
vcube =
3.6523
>> nl = vcyl/vcube
nl =
192.6796
Create an m-file to solve Exercise 1.
We created the following file named PingPong.m:
% PingPong.m - computes a lower bound on the number of
% ping pong balls that fit into a cylinder
% Note that most lines end with a ";", so they don't print
% intermediate results
d = 1.54;
h = 14;
b = 8;
vcyl = h*pi*(b/2)^2;
vcube = d^3;
nl = vcyl/vcube
When run from the command line, this program produces the following output:
>> PingPong
nl =
192.6796
To complicate your problem, suppose that you have not been given values for
One way to automate the computation of
Add a for loop to your m-file from Exercise 2 to compute
This solution is by BrieAnne Davis.
for d=1.0:.05:2.0
b=8;
h=14;
vcyl=h*pi*(b/2)^2
vcube=d^3
nl=vcyl/vcube
end
Modify your m-file from Exercise 3 to plot
This solution is by Wade Stevens. Note that it uses the command hold on to plot each point individually in the for loop.
clear all
hold on
for d=1.0:0.1:2.0;
b=8;
h=14;
C=h*pi*(b/2)^2; %volume of cylinder
c=d^3; %volume of cube
N=C/c; %Lower bound
floor(N)
plot (d,N,'g*')
end
This solution creates the plot in Figure 1.
|
This different solution is by Christopher Embrey. It uses the index variable j to step through the dv array to compute elements of the nlv array; the complete nlv array is computed, and then plotted outside the for loop.
clear
dv=1.0:.05:2.0;
[junk,dvsize] = size(dv)
for j=1:dvsize
d=dv(j)
b=8; %in
h=14; %in
vcyl=h*pi*(b/2)^2;
vcube=d^3;
nl=vcyl/vcube;
nlv(j)=nl;
end
plot (dv,nlv)
This solution creates the plot in Figure 2.
|
And finally, this solution by Travis Venson uses vector computations to perform the computation without a for loop.
%creates a vector for diameter
dv=1:.02:2;
b=5.5;
h=12;
%computes volume of cylinder
vcyl=h*pi*(b/2)^2;
%computes volume of cube
vcube=dv.^3;
%computes lower bound
lowerboundv=vcyl./vcube;
%plots results
plot(dv,lowerboundv)
Modify your m-file from Exercise 3 to compute
This solution is by AJ Smith. The height, h, ranges from 12 to 15 and the base, b, ranges from 8 to 12.
for h=12:15; %ranges of height
for b=8:12; %ranges of the base
d=1.54; %diameter of ping pong ball.
Vcyl=h*pi*(b/2)^2; %Volume of cylinder
Vcube=d^3; %volume of a cube that encloses a single ball
Nl=Vcyl/Vcube %lower bound on the number of balls that fit in the cylinder
end
end