0

I have a function that returns multiple values:

function [a,b,c] = f()
  a = 1; b = 2; c = 3;
end

How to I save the output into a vector without having to create intermediate variables? Example shown below:

> z = zeros(1,3);
> [a,b,c] = f();
> z(:) = [a,b,c];
> z
ans =

   1   2   3

I don't have to define intermediate variables a, b, c, but only if I define an additional cell array:

> ce = cell(1, 3);
> [ce{:}] = f();
> z(:) = cell2mat(ce);
> z
ans =

   1   2   3

Is there a better way to go directly from z(:) = f()?

hatmatrix
  • 42,883
  • 45
  • 137
  • 231
  • 2
    Don't create those variables in the first place. Just create a single array containing all those variables – Sardar Usama Apr 15 '18 at 12:17
  • Multiple return values may have different sizes, how do you want to concatenate them into an array? This syntax is allowed : `[z(1),z(2),z(3)]=f();` – rahnema1 Apr 15 '18 at 14:58
  • You can use [varargout](http://it.mathworks.com/help/matlab/ref/varargout.html) to manage the type and number of output variables. You can find an example in this my [answer to a similar question](https://stackoverflow.com/a/48671290/4806927). – il_raffa Apr 15 '18 at 16:32
  • These are all good suggestions... but what if I didn't write the function? The `[z(1), z(2), ...] = f()` is likely the most direct solution. – hatmatrix Apr 15 '18 at 22:05

0 Answers0