Simple if else function

14 views (last 30 days)
Vasavi_Shakti
Vasavi_Shakti on 6 Feb 2018
Commented: Walter Roberson on 6 Feb 2018
Hello People,
I'm new into Matlab, and i'm trying to write af simple if-else function. My function af has 3 input variables: - figur=rektangel, trekant or ellipse (to calculate the moment of inertia of said geometry) - b = width - h = height
So for example, if i my input was: [Ix0,Iy0] = inertimoment(rektangle,2,2), it should calculate the moment of inertia of a rectangle of height anf width of 2.
But whenever i run the function, i get an error, that says "undefined function or variable figur"
function [Ix0,Iy0] = inertimoment(figur,b,h)
if strcmp(figur, 'rektangel')
Ix0 = (b*h^3)/12;
Iy0 = (b^3*h)/12;
ifelse strcmp(figur, 'trekant')
Ix0 = b*h^3/36;
Iy0 = b^3*h/36;
else strcmp(figur, 'ellipse')
Ix0 = pi*b*h^3/64;
Iy0 = pi*b^3*h/64;
end

Accepted Answer

Jos (10584)
Jos (10584) on 6 Feb 2018
You should call the function like this
[out1, out2] = inertimoment('rektangel', 3, pi)
By the way, the else in your code should also become an elseif !
Finally, add an else block that is executed when the variable figure is not matched to any of the three options.
  2 Comments
Vasavi_Shakti
Vasavi_Shakti on 6 Feb 2018
Thank you for your answer, it worked! I've now entered af last else, if a fourth kind of geometrical object is the input. But now it says that there aren't enough inputs? Shouldn't a single input (instead of 3) be wrong enough to skip the first three conditions?
function [Ix0,Iy0] = inertimoment(figur,b,h)
if strcmp(figur, 'rektangel')
Ix0 = (b*h^3)/12;
Iy0 = (b^3*h)/12;
elseif strcmp(figur, 'trekant')
Ix0 = b*h^3/36;
Iy0 = b^3*h/36;
elseif strcmp(figur, 'ellipse')
Ix0 = pi*b*h^3/64;
Iy0 = pi*b^3*h/64;
else
disp('Unavailable geometry!')
end
Walter Roberson
Walter Roberson on 6 Feb 2018
"Shouldn't a single input (instead of 3) be wrong enough to skip the first three conditions?"
No. In MATLAB it is legal and often convenient to define a function as accepting multiple inputs but to not require that all of the trailing inputs be provided by the user. This is fine as long as the code does not need those inputs. For example if you supported circle then it would need only a radius so it would not make sense to force the user to provide an third unused parameter for that case.
You can test whether a parameter was provided and take steps. For example you could do
if ~exist('b', 'var') || isempty(b)
b = 10;
end
if ~exist('h', 'var') || isempty(h)
h = 15;
end
and then if the user did not provide b or provided empty b then the default value 10 would be used instead.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!