Simple if else function
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Vasavi_Shakti
le 6 Fév 2018
Commenté : Walter Roberson
le 6 Fév 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
0 commentaires
Réponse acceptée
Jos (10584)
le 6 Fév 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 commentaires
Walter Roberson
le 6 Fév 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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Surface and Mesh Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!