How to acess the Data of a struct with a variable

8 Ansichten (letzte 30 Tage)
Lukas
Lukas am 3 Mär. 2014
Kommentiert: Lukas am 17 Mär. 2014
for example a struct contains another struct and I want to acess the content of the second struct the struct looks like:
Data.Sens1.current=[2]
Data.Sens2.current=[4]
Data.Sens3.current=[5]
...
Data.Sensn.current =[9]
now i want to assign the content of the Sensors to anothe variable. i can do it this way
data(1)=Data.Sens_one.current
data(2)=Data.Sens_two.current
this way is very laborious. Is there an easy way to assign the Content of a struct with a for queue and set Sens_one.current, Sens_two.current ... as a char vector. this was doesn't seem to work
sens_vector=['Sens_one.current';'Sens_two.current';'Sens_two.current';...]
for i=1:n
date(i)=Data.(sens_vector(i,:))
end
I can only acess the Date in the inner struct with structName.(dynamicExpression) like the matlap help "Generate Field Names from Variables" here in my example
A=['current']
data.Sens1.(A)
but this way doesn't seem to work if I want to acess the first struct like
A=['Sens1.current']
data.(A)
Can I acess the Data my way or does anyone know another way? Thanks in advance

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 3 Mär. 2014
fn = fieldnames(Data);
for K = 1 : length(fn)
thisfield = fn{K};
sensnum = str2double( regexp(thisfield, '\d+', 'match') );
data(sensnum) = Data.(thisfield).current;
end
You could probably also do something with struct2cell

Weitere Antworten (1)

Tim leonard
Tim leonard am 12 Mär. 2014
Data.Sens1.current=[2]
Data.Sens2.current=[4]
Data.Sens3.current=[5]
Data.Sens4.current =[6]
Data.Sens5.current =[7]
Data.Sens6.current =[8]
Data.Sens7.current =[9]
Data.Sens8.current =[10]
Data.Sens9.current =[11]
%cellfun + Dynamic Structure Naming
arrayOut = cellfun(@(nameIn)(Data.(nameIn).current),fieldnames(Data));
arrayOut'
% ans =
% 2 4 5 6 7 8 9 10 11

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by