4

Say I have a function whose outputs are two reals a and b

[a,b]=function(c)

I'd like to get all the outputs in a vector v. v=function(c) doesn't do what I want, v is 'a' only. Of course here I could do v=[a,b]. But the function in question is ind2sub for a N-D array so it gives n outputs that I'd like to have in a vector directly.

Is there a way to do it? Thanks very much!

Eitan T
  • 32,660
  • 14
  • 72
  • 109
JuliaR
  • 99
  • 5

1 Answers1

2

You can use a cell array and a comma-separated list like so:

X = cell(N, 1);
[X{:}] = function(C);

The syntax X{:} is in fact expanded to [X{1}, X{2}, ...], which provides a valid sink for your function. As a result, each output variable will be stored in a different cell in X.

If each output variable is a scalar, you can flatten out the cell array into a vector by using yet another comma-separated list expansion:

v = [X{:}];
Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • Thanks! Comma-separated lists help a lot! – JuliaR Jun 05 '13 at 15:35
  • Or you could use cell2mat at the end. Or you could write a function that will do it for you. The nice thing about a tool like MATLAB is you can customize it to do what you like in this way, adding your own desired functionality as needed. –  Jun 05 '13 at 15:37
  • @woodchips in my experience, Mathematica, R and xlisp-stat are all vastly superior to Matlab for customization. Matlab's syntax is too clunky (e.g. this question is *very* difficult to answer for even very experienced Matlab users). – John Jun 05 '13 at 18:46
  • @John - and that is why it helps to write a helper function, writing it only once, rather than having to remember the trick. I'll agree, in this case, the syntax is not trivial, but overall, I prefer MATLAB to some of the others you mention. THis is just personal preference of course, and it will vary for every person. –  Jun 05 '13 at 21:07
  • 1
    @JuliaR Remember to accept the answers if they have worked for you! – Ander Biguri Mar 20 '15 at 10:51