How to acess the Data of a struct with a variable

4 views (last 30 days)
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

Accepted Answer

Walter Roberson
Walter Roberson on 3 Mar 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

More Answers (1)

Tim leonard
Tim leonard on 12 Mar 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

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!