access outputs of functions with multiple outputs

1 回表示 (過去 30 日間)
gg
gg 2012 年 9 月 6 日
Dear All,
I would like to find a functional way to access outputs of functions with multiple outputs. Assume I have a function "twout" defined in a m-file as follows
function [foo, bar] = twout(x, y)
foo = x+y;
bar = x-y;
end
I would like now to access the SECOND output "bar" from a function handle, i.e. I am looking for a function (or something which can be put into an anonymous function) called "somemagic" say, such that an anonymous function can be defined as
anoneout = @(x,y)( somemagic( twout(x, y) )
and the call
@anoneout(1,2)
produces -1.
It is clear that I can always
  • write anoneout into a separate .m-file where I make a proper call to twout
  • switch "foo" and "bar" in the function definition.
  • return a structured data type instead of 2 outputs
My question is really whether these workaroounds are indeed the only solutions.
Thanks
gg

採用された回答

Matt Fig
Matt Fig 2012 年 9 月 6 日
編集済み: Matt Fig 2012 年 9 月 6 日
There is a way to do it, but I am reluctant to share it because I don't think it is worthwhile to program this way. I cannot think of any reason one would want to do this, except to see if it could be done. Since I am that kind of curious person, I will show how to do it, but again I think you should go another route!
>> f = @(x,y,r) evalin('caller',[sprintf('[~,x]=twout(%.15f,%.15f);',x,y),r,'=x;'])
>> f(2,3,'r') % Third arg is a string: [~,r] = twout(2,3)
>> r
r =
-1
  3 件のコメント
Jan
Jan 2012 年 9 月 6 日
Nice, or ugly.
Matt Fig
Matt Fig 2012 年 9 月 6 日
Definitely ugly, and I wouldn't ever use it!

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

その他の回答 (1 件)

Jan
Jan 2012 年 9 月 6 日
I'm not sure if I understand the question. Do you want something like this:
function Out2 = SomeMagic(Fcn, varargin)
[Out1, Out2] = feval(Fcn(vargargin{:}));
% Note: FEVAL can be omitted in modern Matlab versions
This would be called by:
z = SomeMagic(@twout, x, y);
But I do not think that this is useful, such that I assume, you are looking for something else.
  3 件のコメント
Jan
Jan 2012 年 9 月 6 日
編集済み: Jan 2012 年 9 月 6 日
I think this is not useful, because it does not add any new functionality to Matlab. The first output is still calcutate, but the command to ignore it is hidden in a function. The following would be nicer, leaner, faster and easier to debug:
[dummy, z] = twout(x, y);
Or when you do not need to write code compatible to old versions, replace "dummy" by "~".
gg
gg 2012 年 9 月 6 日
Sure, but this does not work if you want to call twout in an anonymous function!

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

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by