Calling a function without an Output argument

Hi Programmers,
I have a function that plots the phase and magnitude of my signal.
I want this function to plot only the magnitude if no ouput argument is provided when the function is called.
Y = Myplot (a,b)
Y = figure(1)
subplot(2,1,1)
stem (a)
subplot(2,1,2)
stem (b)
% I want to plot only stem (a) when the function is called without the
% output argument.
Myplot (a,b)
stem (a)

 採用された回答

Adam Danz
Adam Danz 2021 年 4 月 5 日
編集済み: Adam Danz 2021 年 4 月 5 日

0 投票

Use nargout to determine the number of output arguments.
if nargout==0
% do something
elseif nargout < 2
% do something else
end

4 件のコメント

Telema Harry
Telema Harry 2021 年 4 月 5 日
Thank you.
Adam Danz
Adam Danz 2021 年 4 月 5 日
編集済み: Adam Danz 2021 年 4 月 5 日
Note that if the function call is not followed by a semicolon to suppress the output or if the function is used as an input in an array or in another function, then even if an output isn't explicitly assigned nargout will return 1.
For example,
T = [1, 2, f(n)];
Telema Harry
Telema Harry 2021 年 4 月 5 日
I modified the code slightly and it gave me the intended result.
if nargout==0
% do something
elseif nargout > 0
% do something else
end
Thank you for your help.
Adam Danz
Adam Danz 2021 年 4 月 6 日
This can be simplified to
if nargout == 0
else
end

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2021 年 4 月 5 日

0 投票

Change the number of input arguments instead
function y=Myplot(varagin)
y=figure;
if nargin==2
subplot(2,1,1);
stem(varagin{1});
subplot(2,1,2);
stem(varagin{2});
else
stem(varagin{1});
end

カテゴリ

製品

リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by