Info

This question is closed. Reopen it to edit or answer.

I want to load sever flies and save them to individual variables not located in a single structure or cell.

1 view (last 30 days)
I have several CSV files that I want to import into my workspace each named to a different variable. For example I have Scenario1.csv through Scenarion32.csv. I want so save to variables a1 though a32. all individually saved and not located in a single structure or cell. I would like to do this in a for loop. This is what I have tried.
d = dir('*.csv');
Number_mat = length(d);
for i=1:32
a(i).data= readtable(['Scenario' num2str(i) '.csv']);
end
  1 Comment
Stephen23
Stephen23 on 6 Jul 2020
Edited: Stephen23 on 6 Jul 2020
Rather than creating a second structure array and inefficiently expanding it on each loop iteration, it is better and more efficient to store the data in the structure array that you already have:
D = 'path to the directory where the files are saved';
S = dir(fullfile(D,'*.csv'));
N = numel(S);
for k = 1:N
F = fullfile(D,S(k).name);
S(k).data = readtable(F);
end
Why do you use dir to get a list of the filenames, which you then do not use?
Why do you use length (tip: better to use numel) to count the number of files, which you also do not use?
"..and not located in a single structure or cell."
Why?

Answers (1)

madhan ravi
madhan ravi on 6 Jul 2020
Edited: madhan ravi on 6 Jul 2020
Here's why you shouldn't!!
d = dir('*.csv');
n = numel(d);
a = cell(n, 1);
for k = 1 : n
a{k} = readtable(sprintf('Scenario%d.csv', k));
end
  4 Comments
JC
JC on 6 Jul 2020
So I need to also create X variables for the first column in in each table. So I would like X1 through X32
Stephen23
Stephen23 on 6 Jul 2020
Edited: Stephen23 on 6 Jul 2020
"How can I acess these variables once they are loaded."
Using basic indexing:
"So I need to also create X variables for the first column in in each table. So I would like X1 through X32"
I don't see why you "need" to do that. So far everything you have described could be done much more simply and more efficiently using basic indexing. Have you tried using indexing?

Tags

Community Treasure Hunt

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

Start Hunting!