Home > OS >  How do I split results into separate variables in matlab?
How do I split results into separate variables in matlab?

Time:09-14

I'm pretty new to matlab, so I'm guessing there is some shortcut way to do this but I cant seem to find it

results = eqs\soltns;

A = results(1);
B = results(2);
C = results(3);
D = results(4);
E = results(5);
F = results(6);

soltns is a 6x1 vector and eqs is a 6x6 matrix, and I want the results of the operation in their own separate variables. It didn't let me save it like

[A, B, C, D, E, F] = eqs\soltns;

Which I feel like would make sense, but it doesn't work.

CodePudding user response:

Up to now, I have never come across a MATLAB function doing this directly (but maybe I'm missing something?). So, my solution would be to write a function distribute on my own.

E.g. as follows:

result = [ 1 2 3 4 5 6 ];
[A,B,C,D,E,F] = distribute( result );

function varargout = distribute( vals )
  assert( nargout <= numel( vals ), 'To many output arguments' ) 
  varargout = arrayfun( @(X) {X}, vals(:) );
end

Explanation:

  1. nargout is special variable in MATLAB function calls. Its value is equal to the number of output parameters that distribute is called with. So, the check nargout <= numel( vals ) evaluates if enough elements are given in vals to distribute them to the output variables and raises an assertion otherwise.

  2. arrayfun( @(X) {X}, vals(:) ) converts vals to a cell array. The conversion is necessary as varargout is also a special variable in MATLAB's function calls, which must be a cell array.

  3. The special thing about varargout is that MATLAB assigns the individual cells of varargout to the individual output parameters, i.e. in the above call to [A,B,C,D,E,F] as desired.


Note: In general, I think such expanding of variables is seldom useful. MATLAB is optimized for processing of arrays, separating them to individual variables often only complicates things.


Note 2: If result is a cell array, i.e. result = {1,2,3,4,5,6}, MATLAB actually allows to split its cells by [A,B,C,D,E,F] = result{:};

CodePudding user response:

One way as long as you know the size of results in advance:

results = num2cell(eqs\soltns);
[A,B,C,D,E,F] = results{:};

This has to be done in two steps because MATLAB does not allow for indexing directly the results of a function call.

But note that this method is hard to generalize for arbitrary sizes. If the size of results is unknown in advance, it would probably be best to leave results as a vector in your downstream code.

  • Related