Importing .csv with forloop
13 views (last 30 days)
Show older comments
Elise Baribault
on 6 Jul 2021
Commented: Walter Roberson
on 6 Jul 2021
I have multiple .csv files that I want to import into Matlab using a forloop to avoid doing it by hand. My .csv files are named FILENAME23.csv, FILENAME46.csv, FILENAME69.csv, etc.
for i = 23:23:2001
Test = xlsread(sprintf('FILENAME%d.csv',i));
end
I used the xlsread function to import, but now I am trying to get the data saved as different variables each time. Right now, the above works, but "Test" is being rewritten. If I change "Test" to "Test(i)" I get an error:
"Unable to perform assignment because the indices on the left side are not compatible with the size of the right side." Please help!
0 Comments
Accepted Answer
Walter Roberson
on 6 Jul 2021
filenums = 23:23:2001;
numfiles = length(filenums);
Test = cell(numfiles,1);
for idx = 1 : numfiles
i = filenums(idx);
Test{idx} = xlsread(sprintf('FILENAME%d.csv',i));
end
We recommend that you consider switching to readtable() or readmatrix() instead of xlsread()
3 Comments
Walter Roberson
on 6 Jul 2021
nd = ndims(Test{1,1})+1;
total = sum(cat(nd, Test{:}), nd);
This will work provided that the entries in Test are of consistent size, but this code does not require that the data be aligned as rows or columns or any particular dimension.
For the particular case you have,
total = sum([Test{:}],2)
is the shortcut.
More Answers (0)
See Also
Categories
Find more on Spreadsheets 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!