Convert struct to matrix MATLAB

Jespar picture Jespar · Jan 9, 2017 · Viewed 8.2k times · Source

Is there a way to convert a struct (2 fields with 52 variables each) to a matrix (2x52)? Thank you

struct:

    sym (1x53)
    prob (1x53)

I have tried the following which gives me a 1 x 1 cell array

symProb = reshape({x.sym}, size(53)); 

I have also tried struct2cell which does the same.

Answer

Suever picture Suever · Jan 9, 2017

Probably the easiest thing (since it's only two fields), is to simply concatenate them along the first dimension using cat

result = cat(1, x.sym, x.prob);

Or you could just use [] and ;

result = [x.sym; x.prob]

If you want a more general solution, you could use struct2array with some reshaping

result = reshape(struct2array(x), [], numel(x)).';

Note that all of this assumes that the data within sym and prob are actually the same datatype and therefore able to be placed within the same array, otherwise a cell array is the only way to hold both fields.

Also your code is yielding a 1 x 1 cell array because you're wrapping your data x.sym inside of a 1 x 1 cell array.