2

Is there an idiomatic way in Matlab to bind the value of an expression to the nth return value of another expression?

For example, say I want an array of indices corresponding to the maximum value of a number of vectors stored in a cell array. I can do that by

function I = max_index(varargin)
    [~,I]=max(varargin{:});

cellfun(@max_index, my_data);

But this requires one to define a function (max_index) specific for each case one wants to select a particular return value in an expression. I can of course define a generic function that does what I want:

function y = nth_return(n,fun,varargin)
    [vals{1:n}] = fun(varargin{:});
    y = vals{n};

And call it like:

cellfun(@(x) nth_return(2,@max,x), my_data)

Adding such functions, however, makes code snippets less portable and harder to understand. Is there an idiomatic to achieve the same result without having to rely on the custom nth_return function?

digitalvision
  • 2,552
  • 19
  • 23
  • Why would you want to do this? Since you already know which return value you want to store, what is the problem with the [~,I] syntax? – mmumboss Mar 23 '13 at 14:10
  • AFAIK, the [~,I] syntax is not usable as part of an expression. I.e. I can not use it in an anonymous function, like in the cellfun() call above. – digitalvision Mar 23 '13 at 14:17

1 Answers1

2

This is as far as I know not possible in another way as with the solutions you mention. So just use the syntax:

[~,I]=max(var);

Or indeed create an extra function. But I would also suggest against this. Just write the extra line of code, in case you want to use the output in another function. I found two earlier questions on stackoverflow, which adress the same topic, and seem to confirm that this is not possible.

Skipping outputs with anonymous function in MATLAB

How to elegantly ignore some return values of a MATLAB function?

The reason why the ~ operator was added to MATLAB some versions ago was to prevent you from saving variables you do not need. If there would be a syntax like the one you are searching for, this would not have been necessary.

Community
  • 1
  • 1
mmumboss
  • 690
  • 1
  • 5
  • 13
  • Thank you. It seems you are correct. The [~,ans]=max(x) is unfortunately not supported as an expression though, making it necessary to define an extra function. – digitalvision Mar 23 '13 at 17:05