how do I get only 1 variable passed through a function?
3 ビュー (過去 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);
0 件のコメント
回答 (1 件)
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 件のコメント
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 Center および File Exchange で Simulink Functions についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!