Check which output arguments are requested within a function

28 次查看(过去 30 天)
I have a custom function that returns multiple arguments, say:
function [arg1, arg2, arg3, arg4] = myfun(x,y,z)
% Code
end
Now, we can call that function e.g. in such way:
[A, B, ~, D] = myfun(3,2,1)
If we make such call, no value has to be assigned to variable arg3 within myfun. I want to know if there is a way to check within the function body which output arguments have been called (same as arg1, arg2, arg4 above), and which outputs have been neglected (i.e. arg3 which is called with tilde).
There is a number of functions dealing with i/o arguments, but I haven't been able to find a solution to this question in the documentation of 2015a version.
  1 个评论
Adam
Adam 2017-8-23
Have you nosied into the code of Matlab functions that do this to see what they do? I don't know off-hand. They may just calculate all results anyway or they may have a more intelligent method.
Certainly nargout is not of use here since you are requesting non-contiguous output arguments.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2017-8-23
编辑:Stephen23 2017-8-23

更多回答(1 个)

Jan
Jan 2017-8-23
You can implement this manually:
function Out = myfun(x,y,z, Want)
% Want: cell string containing the names of the wanted outputs:
if any(strcmpi(Want, 'A'))
Out.A = rand(1);
end
if any(strcmpi(Want, 'B'))
Out.B = 'any string';
end
...
end
And automatic solution with identifying the "~" would be much nicer. Note that Matlab does have this information during the runtime already, but there is no way to provide this detail to the called function. I assume this is built into the design of Matlab, because this would require forwarding information to a function, which is used in the future -- after leaving the function.
You can send an enhancement request to MathWorks.

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by