How to use multiple struct files using for loop

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 Comment

"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.

Sign in to comment.

Answers (2)

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.
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

Asked:

on 25 Sep 2017

Answered:

on 25 Sep 2017

Community Treasure Hunt

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

Start Hunting!