0

The matlab function sscanf returns a variable size matrix (or perhaps a cell array?) which can be assigned to a matrix of variable names

>> clear all ;
line = '1 2' ;
[a, sz] = sscanf( line, '%d %d' ) ;

It appears that the output matrix a is a column matrix, which can be transposed to form a 1x2 matrix:

b = a' ;

I'd like to be able to assign this to an matrix of variable names, like I can do in the preceding sscanf call. I figured I'd be able to do:

[c,d] = b ;

but this gives me the error:

Too many output arguments.

From the answer https://stackoverflow.com/a/23800927/189270 it looked like I may be able to do this by transforming the matrix a into a cell array, however, I don't seem to be able to figure out the right syntax for this:

>> num2cell(a)

ans =

    [1]
    [2]

>> [c,d] = num2cell(a)
Error using num2cell
Too many output arguments.

>> [c,d] = num2cell(a')
Error using num2cell
Too many output arguments.

>> [c ; d] = num2cell(a)
 [c ; d] = num2cell(a)
  |

I can solve the problem by brute force by assigning to the fields b, c one at a time indexing into the matrix a. However, I imagine this is a common type of bulk variable assignment (I do this in Mathematica for example), so I wanted to understand what is wrong with my attempts above, and what the correct matlab syntax for this is.

Community
  • 1
  • 1
Peeter Joot
  • 7,848
  • 7
  • 48
  • 82

1 Answers1

0

You almost have it correct. Once you take your numbers and convert them into individual cells in a cell array (through num2cell), use deal to distribute each element in your cell array to your corresponding variables. As such:

%// Your code
line = '1 2' ;
[a, sz] = sscanf( line, '%d %d' ) ;

%// New code!
b = num2cell(a);
[c,d] = deal(b{:});

This is what I get after deal:

c =

     1


d =

     2
rayryeng
  • 102,964
  • 22
  • 184
  • 193