Borrar filtros
Borrar filtros

How to acess the Data of a struct with a variable

3 visualizaciones (últimos 30 días)
Lukas
Lukas el 3 de Mzo. de 2014
Comentada: Lukas el 17 de Mzo. de 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

Respuesta aceptada

Walter Roberson
Walter Roberson el 3 de Mzo. de 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

Más respuestas (1)

Tim leonard
Tim leonard el 12 de Mzo. de 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

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by