how do I get only 1 variable passed through a function?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
James Tursa
am 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 Kommentare
James Tursa
am 15 Mai 2020
Bearbeitet: James Tursa
am 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.
Siehe auch
Kategorien
Mehr zu Simulink Functions finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!