Using a String to select a structure in a .mat file
7 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I was given a .mat file that contains structures named:
c1_01, c1_02, c1_03,c1_04,..., c1_14
All these structures have some data inside that I need extracted individually and add a new field to that stucture that is:
c1_01.r = (some variable in my script)
where the variable is calculated in the script. I need to do this for all the data and at the end, save the entire .mat file so that the new field is saved.
The issue I am running into is actually the iteration through these structures. I have tried using
i = 1:14
if(i<10);
name = sprintf('c1_0%d',i);
end
if(i>=10)
name = sprintf('c1_%d',i);
end
fx = name.force; %force is the name of a field in the structure.
Is there anyway to iterate through structures in this manner? How can I go about solving this?
4 件のコメント
Adam Danz
2019 年 12 月 3 日
編集済み: Adam Danz
2019 年 12 月 3 日
Hmmm....
Off the top of my head, maybe you can load the variables in as a structure using S = load(___). Assuming all of the loaded variables are c1_01, c1_02, c1_03, etc, they would be fields of S and you could merely loop through the fields using
fn = fieldnames(S);
for i = 1:numel(fn)
C = S(fn{i}); % the i-th field in S
end
*fixed typos (blush)
J. Alex Lee
2019 年 12 月 3 日
I'm sure you'll figure out the minor typos, but I think rather:
S = load("filename.mat");
fn = fieldnames(S);
for i = 1:numel(fn)
C = S.(fn{i}); % the i-th field in S
end
If you need access to the value of "i" for your script to generate the right data for the .r field you wish to append, you could also do (and using Adam's suggestion of structure array for easier future processing)
S = load("filename.mat");
for i = 14:-1:1
C(i) = S.(sprintf('c1_%01d',i)))
C(i).r = mynewdata;
end
save("newfile.mat","C")
If you have to stick with the current scheme then I think this would work
S = load("filename.mat");
for i = 1:14
C = S.(sprintf('c1_%01d',i)))
C.r = mynewdata;
S.(sprintf('c1_%01d',i))) = C;
end
save("newfilename.mat","-struct","S")
回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!