How to acess the Data of a struct with a variable
4 ビュー (過去 30 日間)
古いコメントを表示
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
0 件のコメント
採用された回答
Walter Roberson
2014 年 3 月 3 日
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
その他の回答 (1 件)
Tim leonard
2014 年 3 月 12 日
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Data Type Conversion についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!