Configure the number of exits from the function call without setting the output variables

For any function, I can dictate the return variables by explicitly defining how many outputs I expect [out1,out2,...,outn] = ...

Edit: being able to maximize the potential of #outputs would also be helpful

An example of a problem

The following code does exactly what is expected (yes it is redundant with myArray(IND) = 1;

)

[I,J] = ind2sub(size(myArray),IND)
myArray(I,J) = 1;

      

When I try to pass arguments to a function directly, I get no results I wannt

myArray(ind2sub(size(myArray),IND)) = 1;

      

I really get myArray(I) = 1;

it when I wantedmyArray(I,J) = 1;

Question

How can I determine how many return variables are returned without explicitly defining my output arguments?

I expect some function in the family eval()

or some kind of cast [],{},(:), etc.

to do the trick, but I haven't seen any documentation or gotten any of them to work.

+3


source to share


1 answer


The immediate problem with using the output ind2sub

directly as an index in myArray

without an intermediate variable is that when indexing the myArray

query, ind2sub

only the first output is requested ind2sub

. The first output is then used as a linear index for indexing in myArray

and assigning values, resulting in unexpected behavior.

Instead, you can use a cell array to capture as many outputs as possible and then rely on indexing {}

to get a comma-separated list .

[outputs{1:ndims(myArray)}] = ind2sub(size(myArray), IND);

      

Then you can use this cell array containing all outputs to move all values ​​as inputs or indices elsewhere:

myArray(outputs{:}) = 1;

      



In the example above, you don't really need to do anything, as you can directly use linear indexes IND

to index into myArray

. In fact, using inference is likely to give you the wrong assignment, since each index permutation will be used in assigning values, not in elementary subscript pairing . ind2sub

myArray(IND) = 1;

      

In general, you can use this technique in conjunction with nargout

to request all output arguments if there are no variable outputs.

[outputs{1:nargout('func')}] = func(inputs);

      

+5


source







All Articles