How to print all loaded files in the workspace?
8 views (last 30 days)
Show older comments
Hi, I am still new to MatLab and I am currently stuck on how to load in files using a 'for' loop. I can get the loop to work, however it only prints the last data file in the work space and not all of them. Here is my code:
for n = [1,2,4]
filename1 = sprintf('SECR%d0_dt.mat',n);
filename2 = sprintf('SECX%d0_dt.mat',n);
S = load(filename1);
S2 = load(filename2);
end
Where the files I want to input are 'SECR10_dt.mat','SECR20_dt.mat' and 'SECR40_dt.mat' and the same for SECX...
I understand that as there is only a total of six files that it will be easy to just input them separately, but I this code will become useful for me later on.
Any help is greatly appreciated, thanks!
0 Comments
Accepted Answer
Stephen23
on 16 Dec 2019
Edited: Stephen23
on 16 Dec 2019
Adapting the example from the documentation slightly:
V = [1,2,4];
N = numel(V);
C = cell(N,2); % preallocate!
for k = 1:N
f1 = sprintf('SECR%d0_dt.mat',V(k));
f2 = sprintf('SECX%d0_dt.mat',V(k));
C{k,1} = load(f1);
C{k,2} = load(f2);
end
The imported data wil be available in the cell array C:
If all of the load-ed structures have the same fields, then you could convert them into one non-scalar structure, which has some convenient syntaxes for accessing the data:
2 Comments
Stephen23
on 16 Dec 2019
You could use a loop, but for just two names this likely to be more complex.
You could use dir, if that returns the filenames that you require.
Keep in mind that calling sprintf and load twice might be the simplest solution...
More Answers (0)
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!