Reputation: 437
I currently have a 102 x 80 x 2 matrix (102 subjects x 80 trials x 2 sessions). I would like to make each row of this matrix into it's own struct. So in the end I would like 102 x 2 structs (102 subjects and 2 sessions). Within each struct there should be 80 x 1 rows.
How can I write a for loop that separates each row into its own struct?
Thanks in advance for your help.
Upvotes: 0
Views: 49
Reputation: 4195
you can use num2cell
to convert each row into cell and then deal
to fill up the struct:
% random data
X = rand(102,80,2);
% convert each row into a cell
Y = squeeze(num2cell(X,2));
Y = cellfun(@transpose,Y,'UniformOutput',0); % transpose matrices
% initalize struct with desired size
s = struct([]);
s(size(Y,1),size(Y,2)).data = [];
% assign struct values
[s(:).data] = deal(Y{:});
Upvotes: 1
Reputation: 991
Well it can be done with a few lines of code and without a for
loop
% Define matrix
mat = rand(102, 80, 2);
% Define indices for the new struct matrix
[X, Y] = meshgrid(1:2, 1:102);
% Make a struct with your data
mat_struct = arrayfun(@(x, y) struct('data', mat(x, :, y).'), Y, X);
Here mat_struct will be a 102x2 array with the data field each of which contains 1x80 matrix
Upvotes: 0