digitalvision
digitalvision

Reputation: 2622

How can I make the value of an expression equal to a second return value of another expression

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?

Upvotes: 2

Views: 111

Answers (1)

mmumboss
mmumboss

Reputation: 699

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.

Upvotes: 2

Related Questions