Write function with multiple output, like sort()

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일

2 개 추천

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

nvmnghia
nvmnghia 2020년 4월 28일
편집: nvmnghia 2020년 4월 28일
Okay, so is this the only way to do it?
I have some software engineering background, and this is an acceptable way to do it. However, I would prefer something like this:
function a = sort(A)
% bla bla
end
function [a, I] = sort(A)
% bla bla, but also compute I
end
It seems that Matlab can't do this.
It can:
function [a,I] = sort(A)
% bla bla
if nargout>1
%also compute I
end
end
Ah I see. If you tried to have both within the same file, you would get an error
'Function with duplicate name "sort" cannot be defined.'
and if they were in separate files, then MATLAB would just find the closest one and ignore the other one.
In MATLAB, it is up to whoever invokes a function to control which output variables are assigned, and that is where the flexibility lies. If you have some function
function [a, I] = sort(A)
% bla bla, but also compute I
end
you can't force whoever invokes it to request both outputs. It is valid for someone to call this function with just one output argument (which is wonderful). Therefore, if you also have the function
function a = sort(A)
% bla bla
end
and you call
b = sort(A)
how should MATLAB know which sort you are trying to call? MATLAB instead decides on its own, based solely on where the functions are located, and you'd better use syntax which is compatible with the one that MATLAB decides to go with.
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개)

카테고리

도움말 센터File Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품

태그

질문:

2020년 4월 28일

댓글:

2020년 4월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by