how to extract all variables from a struct

355 ビュー (過去 30 日間)
Rajesh
Rajesh 2019 年 7 月 30 日
回答済み: Rajesh 2019 年 7 月 30 日
Capture.JPG
Hi, I wanted to extract all the variables from the struct without having to manually type the headers. In short I want to dissolve the entire struct to differnt variables with their individual header names as the variable name.
Many thanks in Advance

回答 (4 件)

Andrei Bobrov
Andrei Bobrov 2019 年 7 月 30 日
T = struct2table(data_table);
  1 件のコメント
Stephen23
Stephen23 2019 年 7 月 30 日
+1 excellent idea.

サインインしてコメントする。


Peter Jarosi
Peter Jarosi 2019 年 7 月 30 日
編集済み: Peter Jarosi 2019 年 7 月 30 日
I agree with Stephen but if you want a quick solution using an ugly trick:
v = fieldnames(data_table);
for x = 1 : length(v)
myVar = data_table.(v{x})
end
or a little bit less ugly:
for v = fieldnames(data_table)
myVar = data_table.(v{1})
end
  3 件のコメント
Peter Jarosi
Peter Jarosi 2019 年 7 月 30 日
@Stephen Cobeldick : Never mind! Everybody wants to learn from her/his own mistakes. :-)
Peter Jarosi
Peter Jarosi 2019 年 7 月 30 日
@Stephen Cobeldick : Thank you for the anti-pattern link!

サインインしてコメントする。


Rajesh
Rajesh 2019 年 7 月 30 日
編集済み: Rajesh 2019 年 7 月 30 日
a=fieldnames(data_table);
data_table=table2array(data_table);
for k=1:length(data_table(1,:))
eval([a{k} '=data_table(:,k);'])
end
thank you for all the replies...this worked for me.. but i had to use eval...
  2 件のコメント
Stephen23
Stephen23 2019 年 7 月 30 日
編集済み: Stephen23 2019 年 7 月 30 日
"i had to use eval"
I doubt that you "had to use eval". I have written thousands of lines of code and imported thousands of data files of many different formats, and yet I have never needed to use eval.
You just designed your code (or data) badly, such that you force yourself into writing slow, buggy, complex, obfuscated code that is hard to debug:
Jan
Jan 2019 年 7 月 30 日
Using eval is indeed a very bad idea.

サインインしてコメントする。


Rajesh
Rajesh 2019 年 7 月 30 日
thank you for all the good advices.
I needed this code for extracting a large number of test data files, which are proccessed by another tool, and fiinally i get the values as a struct. So as a quick solution just to get the variable output which will be an input to my system model (thermal system).. i have used 'Eval'..
But when i am going to create a tool to automate all these post processing, I will keep in mind to work around 'Eval,
Thanks Again for all the suggestions.

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by