MATLAB: If-elseif-else-end structure doesn’t work properly

if sMATLAB

Hello, I am having some issues with a volume calculating program I am trying to create. For whatever reason, after a volume is calculated, the program does not end, it jumps to the next solid to calculate its volume. For example, if I have just calculated the volume of a sphere, it will then go to the cube function and begin asking for inputs related to that function. I don't understand why it just doesn't end. When the functions are run separately, they end fine. But when ran through the 'main' program (the piece of code below), the issue I mentioned pops up. Any suggestions?
solid = input('Welcome to Volume Calculator - Please enter the solid for which you would like to calculate the volume: ');
if solid == cube
volume = cube(a)
elseif solid == sphere
volume = sphere(r)
elseif solid == prism
volume = prism(a,b,c)
else disp('Only certain solids can be calculated. Please try again')
end

Best Answer

Consider your lines
if solid == cube
volume = cube(a)
The second of those lines shows us that "cube" is a function. In the "volume =" line, the function is invoked with one argument.
Now look again at the first of those lines. "cube" appears there, and we know that "cube" is a function, so when "cube" occurs there, that means to invoke the function "cube" with no arguments, just as if you had written
if solid == cube()
Then whatever is returned from the cube() function will be compared to the value you input for "solid". As those values probably do not match, the "elseif" branch will be invoked, but the code there has the same issue...
I predict that the corrected code would be
solid = input('Welcome to Volume Calculator - Please enter the solid for which you would like to calculate the volume: ', 's');
if strcmpi(solid,'cube')
volume = cube(a)
elseif strcmpi(solid, 'sphere')
volume = sphere(r)
elseif strcmpi(solid, 'prism')
volume = prism(a,b,c)
else disp('Only certain solids can be calculated. Please try again')
end
Related Question