Using a String to select a structure in a .mat file

조회 수: 7 (최근 30일)
Mauricio Gomez
Mauricio Gomez 2019년 12월 2일
편집: Adam Danz 2019년 12월 3일
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
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
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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by