Azzera filtri
Azzera filtri

Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

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

1 visualizzazione (ultimi 30 giorni)
Asim Ismail
Asim Ismail il 16 Ago 2017
Chiuso: MATLAB Answer Bot il 20 Ago 2021
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 Commenti
Stephen23
Stephen23 il 16 Ago 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 il 16 Ago 2017
Modificato: Asim Ismail il 16 Ago 2017
Ok lets ignore the final part (storing them in a cell) and just get structures for each vector of the cell.

Risposte (1)

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

Questa domanda è chiusa.

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by