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

3 views (last 30 days)
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);

Answers (1)

James Tursa
James Tursa on 14 May 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 Comments
Kevin Liu
Kevin Liu on 14 May 2020
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 on 15 May 2020
Edited: James Tursa on 15 May 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.

Sign in to comment.

Categories

Find more on Simulink Functions in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!