# For loop and if statement in MATLAB

5 views (last 30 days)

Show older comments

### Answers (2)

Jim Riggs
on 13 Apr 2018

Edited: Jim Riggs
on 13 Apr 2018

First of all, when calculating the masses you have to MULTIPLY the volume by the density.

You should always verify this using dimensional analysis. For example: the calculation pi*rc^2*lc is the volume of the cylinder and has units of (m^3) if you divide m^3 by kg/m^3, that's the same as multiplying m^3 by m^3/kg and the units you end up with are m^6/kg. Now if you multiply m^3 by Kg/m^3 you end up with Kg, which is the correct unit for mass. so,

volume_cyl = (pi * rc^2 * lc); % cylinder volume in m^3

mass_cyl = (pi * rc^2 * lc)* rho; % cylinder mass in Kg

% (or)

mass_cyl = volume_cyl * rho; % Cylinder mass in Kg

Now, this cylinder volume and mass represents the cylinder without the hole, so it does not change, and therefore, this calculation can be placed outside the FOR loop.

The FOR loop is intended to vary hole size, so the loop index 'i' must be used to define the size of the hole, in this case it is the length of one side of the square hole. You are instructed to make the step size 0.1m, so this can be built into the loop. But, rather than use "i" as the loop index, you might just as well use the variable name for the hole width, "Wr". This gives you

for Wr = 0:.1:1 % start at 0, step by 0.1 up to 1

Inside the for loop, you calculate the mass of the hole and subtract it from the mass of the cylinder

mass_cyl = (pi * rc^2 * lc)* rho; % cylinder mass (Kg)

% put a print statement before the loop to show the problem variables that don't change

fprintf('lc=%f, rho=%f, mass_cyl=%f ...etc \n ',lc, rho, mass_cyl, ...etc)

for Wr = W0:Ws:rc % Wr starts at W0, steps by Ws up to rc

mass_hole = Wr^2*lc*rho; % mass of hole (Kg)

tmass_cyl = mass_cyl - mass_hole % mass of the cylinder with the hole in it (Kg)

% put a print statement inside the loop to see each loop calculation

fprintf('Wr=%f, mass_hole=%f, tmass_cyl=%f \n ',Wr, mass_hole, tmass_cyl)

end

Samantha Cepeda
on 14 Apr 2018

##### 2 Comments

Jim Riggs
on 14 Apr 2018

### See Also

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!