Skip to content Skip to navigation

Connexions

You are here: Home » Content » Programming in MATLAB-A Modeling Example Using For Loops

Navigation

Recently Viewed

This feature requires Javascript to be enabled.

Programming in MATLAB-A Modeling Example Using For Loops

Module by: Darryl Morrell. E-mail the author

User rating (How does the rating system work?)
Ratings

Ratings allow you to judge the quality of modules. If other users have ranked the module then its average rating is displayed below. Ratings are calculated on a scale from one star (Poor) to five stars (Excellent).

How to rate a module

Hover over the star that corresponds to the rating you wish to assign. Click on the star to add your rating. Your rating should be based on the quality of the content. You must have an account and be logged in to rate content.

:
(0 ratings)

Summary: This is an example of using MATLAB to solve a simple engineering modeling problem.

Note: Your browser may not currently support MathML. See our browser support page for additional details. You can always view the correct math in the PDF version.

Note: You are viewing an old version of this document. The latest version is available here.

A Modeling Problem: Counting Ping Pong Balls

Suppose you have a cylinder of height h h with base diameter b b (perhaps an empty pretzel jar), and you wish to know how many ping-pong balls of diameter d d have been placed inside the cylinder. How could you determine this?

Note:

This problem, along with the strategy for computing the lower bound on the number of ping-pong balls, is adapted from (Starfield 1994).

A lower bound for this problem is found as follows:

  • N L N L -Lower bound on the number of balls that fit into the cylinder.
  • V cyl V cyl -The volume of the cylinder.
    V cyl = h π b 2 2 V cyl h π b 2 2 (1)
  • V cube V cube -The volume of a cube that encloses a single ball.
    V cube = d 3 V cube d 3 (2)
The lower bound is found by dividing the volume of the cylinder by the volume of the cube enclosing a single ball.
N L = V cyl V cube N L V cyl V cube (3)

Exercise 1

The interactive approach

You are given the following values:

  • d = 1.54 in d 1.54 in
  • b = 8 in b 8 in
  • h = 14 in h 14 in
Use MATLAB interactively (that is, type commands at the command line prompt) to compute N L N L .

Solution

The following shows commands typed to MATLAB (at the >> prompt) and the output produced by MATLAB:


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

Exercise 2

Using an M-File

Create an M-File to solve Exercise 1.

Solution

We used the MATLAB editor (or any text editor) to create 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 MATLAB 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 d d , b b , and h h . Instead you are required to estimate the number of ping pong balls for many different possible combinations of these variables (perhaps 50 or more combinations). How can you automate this computation?

In MATLAB, one way to automate the computation of N L N L for many different combinations of parameter values is to use a for loop. (Read Programming in MATLAB-For Loops if you are not familiar with the use of for loops in MATLAB.) The following problems ask you to develop several different ways that for loops can be used to automate these computations.

Exercise 3

Use a for loop

Add a for loop to your M-File from Exercise 2 to compute N L N L for b = 8 in b 8 in , h = 14 in h 14 in , and values of d d ranging from 1.0 in to 2.0 in.

Solution

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

Exercise 4

Can you still use a for loop?

Modify your M-File from Exercise 3 to plot N L N L as a function of d d for b = 8 in b 8 in and h = 14 in h 14 in .

Solution

This solution is by Wade Stevens. Note that it uses the MATLAB hold on command 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.
Figure 1: Plot of N L N L as a function of d d ; each point plotted individually.
Figure 1 (StevensPlot.png)

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.
Figure 2: Plot of N L N L as a function of d d ; points plotted as vectors.
Figure 2 (EmbreyPlot.png)

And finally, this solution by Travis Venson uses MATLAB's vector capabilities 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)

Exercise 5

More loops?

Modify your M-File from Exercise 3 to compute N L N L for d = 1.54 in d 1.54 in and various values of b b and h h .

Solution

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

References

  1. Anthony M. Starfield; Karl A. Smith; Andrew L. Bleloch. (1994). How To Model It: Problem Solving for the Computer Age. Edina, MN: Interaction Book Company.

Content actions

Give Feedback:

E-mail the module author | Rate module ( How does the rating system work?)

Rating system

Ratings

Ratings allow you to judge the quality of modules. If other users have ranked the module then its average rating is displayed below. Ratings are calculated on a scale from one star (Poor) to five stars (Excellent).

How to rate a module

Hover over the star that corresponds to the rating you wish to assign. Click on the star to add your rating. Your rating should be based on the quality of the content. You must have an account and be logged in to rate content.

(0 ratings)

Download:

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections directly in Connexions. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need a Connexions account to use 'My Favorites'.

| A lens (?)

Definition of a lens

Lenses

A lens is a custom view of Connexions content. You can think of it as a fancy kind of list that will let you see Connexions through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to Connexions materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual Connexions member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks