How to use multiple struct files using for loop

조회 수: 17 (최근 30일)
Hyojin Kim
Hyojin Kim 2017년 9월 25일
답변: OCDER 2017년 9월 25일
Hi everyone,
I loaded multiple struct files in workspace (for example, file#1, file#2, file#3, file#4..). These files are structs with 10 fields. I would like to use those struct files using for loop (instead plot these files individually). Obviously.. this code below does not work. I tried to use sprintf, but this saves it as a variable, not as a structure. Can you help me figure out how to use multiple struct files using for loop? Thanks!
for i = 1:4
figure(i);
field = fieldnames(file#i)';
v = file#i.(field{9});
t = file#i.(field{10});
plot(t, v, 'k');
end
  댓글 수: 1
Stephen23
Stephen23 2017년 9월 25일
편집: Stephen23 2017년 9월 25일
"I loaded multiple struct files in workspace (for example, file#1, file#2, file#3, file#4..)."
And that is the mistake right there. Always load into a variable. Then you can easily avoid these kind of trivial problems. Read this to know why what you are trying to do is a bad way to write code:
Instead of magically trying to access variable names dynamically, you should use simple and efficient indexing.

댓글을 달려면 로그인하십시오.

답변 (2개)

Stephen23
Stephen23 2017년 9월 25일
Always load into a variable, then you avoid this problem entirely.
Assuming that your .mat files contain the same fieldnames, then you could do this:
D = dir(...);
S = struct([]);
for k = 1:numel(D)
S(k) = load(D(k).name);
end
Then accessing the data is trivially easy, either in a loop:
for k = 1:numel(S)
S(k).data
S(k).time
S(k)....
end
Or by converting the non-scalar structure into a comma-separated list:
[S.time]
{S.name}
Look how easy and efficient it can be to access data. Instead you picked the worst way to import data (into lots of numbered variables) and so you will always find it difficult to access your data.

OCDER
OCDER 2017년 9월 25일
How are you loading your files? To fix this, you have to go one step back to file loading step so that you can loop. Currently, you can't loop efficiently for variables names like file1, file2, file3, etc.
Try something like this instead:
%Load your structure into a cell
file = cell(1, 4);
for k = 1:length(file)
file{k} = load(['file#' num2str(k) '.mat']); %Edit this for your file-naming scheme
end
Now, to access each structure in a loop, use your code with this change:
for i = 1:length(file)
figure(i);
field = fieldnames(file{i});
v = file{i}.(field{9});
t = file{i}.(field{10});
plot(t, v, 'k');
end

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by