フィルターのクリア

Write function with multiple output, like sort()

3 ビュー (過去 30 日間)
nvmnghia
nvmnghia 2020 年 4 月 28 日
コメント済み: Tommy 2020 年 4 月 29 日
B = sort(A);
[B, I] = sort(A);
How can I write such a function? Is it as simple as return both B and I, but the first line just uses B and ignore I, or there's some polymorphism trick under the hood?

採用された回答

Tommy
Tommy 2020 年 4 月 28 日
function [out1, out2, out3] = myfunc
...
end
As an example, this function has 3 outputs. You can call it with
[a, b, c] = myfunc
if you want, or you can use
a = myfunc
to just get out1, or perhaps
[~, b, c] = myfunc
to just get out2 and out3. Inside myfunc, each output simply needs to be assigned a value before the end of the function. Is this what you mean?
  5 件のコメント
Steven Lord
Steven Lord 2020 年 4 月 28 日
You can't force someone to call your function with the desired number of outputs, but you could encourage then to do so or refuse to cooperate if they don't.
function [B, I] = mysort(A)
if nargout < 2
warning('You really should call mysort with two output arguments')
% or
error('You must call mysort with two output arguments')
end
% Do stuff to compute B and I
end
Tommy
Tommy 2020 年 4 月 29 日
That's a good point!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by