how do I get only 1 variable passed through a function?

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

回答(1 个)

James Tursa
James Tursa 2020-5-14
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 个评论
Kevin Liu
Kevin Liu 2020-5-14
my function file is
function [C,E] = circumference(r,a,b)
C = 2*pi*r;
E = pi*(3*(a + b) - sqrt((3*a + b)*(a + 3*b)));
whats nargin? I need both C and E tho
James Tursa
James Tursa 2020-5-15
编辑:James Tursa 2020-5-15
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Simulink Functions 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by