Jespar
Jespar

Reputation: 1026

Convert struct to matrix MATLAB

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.

Upvotes: 1

Views: 10788

Answers (3)

user10596420
user10596420

Reputation: 1

You can use this:

cell2mat(struct2cell(YourStructure))

Upvotes: 0

Mark Brandon
Mark Brandon

Reputation: 1

An alternative approach is as follows:

symVec = [x.sym(:)]
probVec = [x.prob(:)

Upvotes: 0

Suever
Suever

Reputation: 65460

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.

Upvotes: 6

Related Questions