How to access a structure array using a loop?

10 vues (au cours des 30 derniers jours)
Airas Akhtar
Airas Akhtar le 24 Juil 2015
Modifié(e) : Andrei Bobrov le 24 Juil 2015
Hello, I am trying to access the data in a structure array .Since there are multiple groups of data I have allotted a single field in the structure for each group. The problem that I am encountering is that I am not able to access the structure by keeping the field name to be variable.MATLAB thinks of that field variable as the field name instead.How can I work around this issue? The code below shows part of the task that I am trying to do.The actual task is a bit different.
p=struct('p1',{p1});
p=struct('p2',{p2});
p=struct('p3',{p3});
p=struct('p4',{p4});
p=struct('p5',{p5});
p=struct('p6',{p6});
p=struct('p7',{p7});
p=struct('p8',{p8});
p=struct('p9',{p9});
p=struct('p10',{p10});
for i=['p1' 'p2' 'p3' 'p4' 'p5' 'p6' 'p7' 'p8' 'p9' 'p10']
o=p.i
end

Réponse acceptée

Guillaume
Guillaume le 24 Juil 2015
First, note that with your example, at the end p is a structure with just one field 'p10'. To create the structure you want:
p = struct('p1', {p1}, 'p2', {p2}, 'p3', {p3}, ...)
Also note that you don't need to put the field contents into a cell array, unless this content is itself a cell array. so:
p = struct('p1', p1, 'p2', p2, ...)
may work just as well.
Secondly, your for loop is not going to work, ['p1' 'p2' 'p3' ...] is exactly the same as 'p1p2p3....', and i will take in turn the values 'p', then '1', then 'p' again, then '2', etc. You need to use a cell array
Finally, to use dynamic field names, you enclose the variable holding the field name in round brackets ().
So:
p = struct('p1',{p1}, 'p2',{p2}, 'p3',{p3}, 'p4',{p4}), 'p5',{p5}, 'p6',{p6}, 'p7',{p7},
'p8',{p8}, 'p9',{p9}, 'p10',{p10});
for fn = {'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10'}
%or better: for fn = fieldnames(p)'
o = p.(fn{1});
end
  1 commentaire
Airas Akhtar
Airas Akhtar le 24 Juil 2015
Thankyou.The detailed conceptual explanation really helped.

Connectez-vous pour commenter.

Plus de réponses (2)

Azzi Abdelmalek
Azzi Abdelmalek le 24 Juil 2015
s=genvarname(repmat({'p'},1,10),'p')
for k=1:numel(s)
out(k)=data.(s{k})
end

Andrei Bobrov
Andrei Bobrov le 24 Juil 2015
Modifié(e) : Andrei Bobrov le 24 Juil 2015
n = {'p1' 'p2' 'p3' 'p4' 'p5' 'p6' 'p7' 'p8' 'p9' 'p10'}';
d = {p1 p2 p3 p4 p5 p6 p7 p8 p9 p10}';
p = cell2struct(d,n,1);

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!

Translated by