how do I get only 1 variable passed through a function?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi I only want to either r or a,b to show if case 1 or case 2 is chosen but MATLAB returns unrecognized variable a,b if r is chosen and vice versa, how do I only have one variable chosen to be passed through the function?
fprintf('Enter either circle (1) or ellipse (2):\n')
choice = input('','s')
switch choice;
case '1'
fprintf('What is the circle''s radius?\n')
r = input(' ');
case '2'
fprintf('What is the ellipse''s minor and major axis lengths?\n')
a = input('Minor length: ');
b = input('Major length: ');
otherwise
fprintf('Please enter either [1] or [2]');
end
[C,E] = circumference(r,a,b);
0 commentaires
Réponses (1)
James Tursa
le 14 Mai 2020
switch choice;
case '1'
fprintf('What is the circle''s radius?\n')
r = input(' ');
[C,E] = circumference(r);
case '2'
fprintf('What is the ellipse''s minor and major axis lengths?\n')
a = input('Minor length: ');
b = input('Major length: ');
[C,E] = circumference(a,b);
otherwise
fprintf('Please enter either [1] or [2]');
end
Then write circumference to detect the number of inputs:
function c = circumference(a,b)
if( nargin == 1 )
% use a as r
else
% use a and b
end
2 commentaires
James Tursa
le 15 Mai 2020
Modifié(e) : James Tursa
le 15 Mai 2020
Your Question is setup for the user to pick either a circle or an ellipse, so why does your function above work with all three of r, a, and b? Shouldn't it be set up to use either r or a and b? Not all three in a single call. I would have expected it to be something like this:
function C = circumference(a,b) % of circle or ellipse
if( nargin == 1 ) % if the number of input arguments is 1, use circle formula
C = 2*pi*r;
else % the number of input arguments is 2, so use ellipse formula
C = pi*(3*(a + b) - sqrt((3*a + b)*(a + 3*b)));
end
nargin is a function that returns the number of actual input arguments that were given by the caller. There is also a function called nargout that returns the number of actual output arguments requested by the caller.
Voir également
Catégories
En savoir plus sur Simulink Functions dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!