Simple if else function

28 次查看(过去 30 天)
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

采纳的回答

Jos (10584)
Jos (10584) 2018-2-6
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 个评论
Vasavi_Shakti
Vasavi_Shakti 2018-2-6
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 2018-2-6
"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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by