Importing .csv with forloop

13 views (last 30 days)
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!

Accepted Answer

Walter Roberson
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
Elise Baribault
Elise Baribault on 6 Jul 2021
Now I have a "Test" variable with a 3x1 cell, for example. Each of those cells has a 2000x1 double. I want to add up the three doubles. I want to add up Test{1,1} + Test{2,1} + Test{3,1}, but automatically
How do I do that?
Walter Roberson
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.

Sign in to comment.

More Answers (0)

Tags

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!