Why isn't my nested if statement not working
1 view (last 30 days)
Show older comments
Hi I'm very new to matlab and I'm trying to use if statements to solve for the mass moment of inertia but it only seems to work for the first if statement and I'm not sure why.
%This Program inputs direction, shape, and dimensions and output the moment
%of inertia
S = input('Enter shape 1 Sphere 2 Circular disk 3 Cylinder 4 thin Ring: ');
a = input('Please enter specified axis 1x,2y or 3z: ');
m = input('Please enter mass: ');
if S==1 && a==1 || a==2 || a==3
ds = input('Please enter dimensions r: ');
I1 = 2/5*m*ds^2;
elseif S==2 && a==1||a==2
dc = input('Please enter dimensions r: ');
I2 = 1/4*m*dc^2;
elseif S==2 && a==3
dc = input('Please enter dimensions r: ');
I3 = 1/2*m*dc^2;
elseif S==3 && a==1|| a==2
dcy = input('Please enter dimensions[r h]: ');
I4 = m./12*(3.*(dcy(1,1))^2 + dcy(1,2)^2);
elseif S==3 && a==3
dcy = input('Please enter dimensions r: ');
I5 = 1/2*m*dcy^2;
elseif S==4 && a==1 || a==2 || a==3
dt = input('Please enter dimensions: ');
I6 = m*dt^2;
end
0 Comments
Answers (2)
Sebastian
on 6 Feb 2017
Edited: Sebastian
on 6 Feb 2017
I did not check the entire code but it looks like you got your conditions wrong because it always enters the first if for one simple reason. Let's assume that S = 3 (circular disk) and a = 2 (y), which means the program should enter the third elseif but it enters if instead. The conditions are being evaluated from left to right so it is all about the order of operations:
if S == 1 && a == 1 || a == 2 || a == 3
S == 1 evaluates to false
false && a == 1 evaluates to false
false || a == 2 evaluates to true
true || a == 3 evaluates to true
Whatever you do your program will enter if because the entire statement will always evaluate to true. That is why you should bracket the conditions like this and then it works the way it is supposed to:
if S == 1 && (a == 1 || a == 2 || a == 3)
elseif S == 2 && (a == 1 || a ==2 )
elseif S == 2 && a == 3
elseif S == 3 && (a == 1 || a == 2)
elseif S == 3 && a == 3
elseif S == 4 && (a == 1 || a == 2 || a == 3)
0 Comments
Walter Roberson
on 6 Feb 2017
if S==1 && a==1 || a==2 || a==3
happens to mean
if (((S==1 && a==1) || a==2) || a==3)
Not because the && happens to be the first, but because || is the lowest precedence operation https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html
You might possibly want
if S==1 && (a==1 || a==2 || a==3)
0 Comments
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!