Extracting field values from cell array of structures
17 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a cell array of structures. Each structure has the fields : Start, End, Id..
RP_Cell{1,1}.Start = [1 2 3; 4 6 4]
RP_Cell{1,1}.End= [11 7 33; 4 16 9]
RP_Cell{1,1}.Id= [23;-4]
RP_Cell{1,2}.Start = [1 -2 4]
RP_Cell{1,2}.End= [17 6 3]
RP_Cell{1,2}.Id= [5]
.
.
RP_Cell{2,1}.Start = [1 2 87; 4 23 1; 7 3 1]
RP_Cell{2,1}.End= [15 65 21; 35 1 6; 6 3 1]
RP_Cell{2,1}.Id= [9; 34; 56]
.
.
.
.
Now, I want to have the data in the fields separately - Start_List, End_List
Start_List{1,1} = [1 2 3; 4 6 4]
Start_List{1,2} = [1 -2 4]
.
.
Start_List{2,1} = [1 2 87; 4 23 1; 7 3 1]
.
End_List{1,1} = [11 7 33; 4 16 9]
End_List{1,2} = [17 6 3]
.
.
End_List{2,1} = [15 65 21; 35 1 6; 6 3 1]
.
How do I do this in the simplest way without using loops
2 commentaires
Réponse acceptée
Guillaume
le 14 Juil 2016
Assuming that all cells of the RP_Cell cell array only contain a scalar structure with the same fields in the same order, you can transform the cell array into a structure array:
RP_Array = cell2mat(RP_Cell);
It is then trivial to transform that structure array into a cell array with struct2cell.
fnames = fieldnames(RP_Array);
Allfields = struct2cell(RP_Array); %Creates a numfield x M x N cell array
%Allfields(1, :, :) corresponds to RP_Array(:, :).(fnames{1})
%Allfields(2, :, :) corresponds to RP_Array(:, :).(fnames{2})
%etc.
Start_List = squeeze(Allfields(strcmp('Start', fieldnames(RP_Array)), :, :));
End_List = squeeze(Allfields(strcmp('End', fieldnames(RP_Array)), :, :));
Note that if you know for sure that Start is the first field of the structure, you can dispense with the strcmp and simply use:
Start_List = squeeze(Allfields(1, :, :));
Using strcmp is safer, since if the order ever happen to change, it will find the correct field.
3 commentaires
Guillaume
le 14 Juil 2016
Modifié(e) : Guillaume
le 14 Juil 2016
So if, RP_cell{1,3} is a 1x2 struct array, e.g.
RP_Cell{1, 3}(1) = struct('Start', [1 2 3;4 5 6], 'End', [10 12; 15 17], 'Id', 4);
RP_Cell{1, 3}(2) = struct('Start', [-1 -2 -3], 'End', [21 23], 'Id', [12;15]);
What should Start_List{1, 3} consists of?
Possibly, you want
Start_List = cellfun(@(c) {c.Start}, RP_Cell, 'UniformOutput', false);
but this will create a cell arrays of cell arrays since you need to store more than one matrix per cell of Start_List.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!