Importing .csv with forloop

13 ビュー (過去 30 日間)
Elise Baribault
Elise Baribault 2021 年 7 月 6 日
コメント済み: Walter Roberson 2021 年 7 月 6 日
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!

採用された回答

Walter Roberson
Walter Roberson 2021 年 7 月 6 日
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 件のコメント
Elise Baribault
Elise Baribault 2021 年 7 月 6 日
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 2021 年 7 月 6 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by