Info

此问题已关闭。 请重新打开它进行编辑或回答。

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

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2017-8-16
" 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 2017-8-16
编辑:Asim Ismail 2017-8-16
Ok lets ignore the final part (storing them in a cell) and just get structures for each vector of the cell.

回答(1 个)

Guillaume
Guillaume 2017-8-16
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 个评论
Guillaume
Guillaume 2017-8-16
Ok then lets just get the results in non-scalar structures.
As said, this is what my answer does.
Asim Ismail
Asim Ismail 2017-8-16
Can it be done in a loop because there are many fields I have to add in the structure?

此问题已关闭。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by