Info

This question is closed. Reopen it to edit or answer.

Make structures from a cell and store them in a new cell

1 view (last 30 days)
I have a function yal which gives a square cell of size nxn, each cell containing a vector of two columns and multiple rows. I want to make structure for each cell, the structures will have:
a.fc=[:,1]; % First column of structure a will store first column of vector
a.sc=[:,2]; % Second column of structure a will store second column of vector
a.addition=[:,1]+[:,2]; % Third column is the sum of both columns of vector
(There can be more fields added to the structure a)
At the end these structures need to be stored in a new cell.
Can anyone please help me out..
  4 Comments
Stephen23
Stephen23 on 16 Aug 2017
" I think storing them in a cell will be more convenient."
Splitting up a perfectly good non-scalar structure into the cells of a cell array will be inefficient, very inconvenient, and most likely a total waste of time.
Asim Ismail
Asim Ismail on 16 Aug 2017
Edited: Asim Ismail on 16 Aug 2017
Ok lets ignore the final part (storing them in a cell) and just get structures for each vector of the cell.

Answers (1)

Guillaume
Guillaume on 16 Aug 2017
As per Stephen's comment using a non-scalar structure as the final result would make a lot more sense (and be a lot easier).
Anyway, to do your conversion the easiest way would be to rearrange your cell array so that the columns of the matrices are actually split into cells of the cell array in the 3rd dimension. A call to cell2struct then do the conversion to structure:
C = arrayfun(@(x) randi([1 25], x, 2), magic(5), 'UniformOutput', false); %generated demo data that fits the bill (nx2 matrix in each cell)
temp = cellfun(@(c) cat(3, {c(:, 1)}, {c(:, 2)}, {c(:, 1) + c(:, 2)}), C, 'UniformOutput', false);
temp = reshape([temp{:}], [size(C), 3]); %the 3 is the number of field
resultstruct = cell2struct(temp, {'fc', 'sc', 'addition'}, 3); %the 3 means use 3rd dimension for fields
If you do really want a cell array of scalar structure then you can do:
resultcell = num2cell(resultstruct);
As said, this would be harder to use.
  7 Comments
Guillaume
Guillaume on 16 Aug 2017
Ok then lets just get the results in non-scalar structures.
As said, this is what my answer does.
Asim Ismail
Asim Ismail on 16 Aug 2017
Can it be done in a loop because there are many fields I have to add in the structure?

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!