フィルターのクリア

loading multiple csv files using readmatrix

30 ビュー (過去 30 日間)
julian gaviria
julian gaviria 2023 年 10 月 19 日
編集済み: Stephen23 2023 年 10 月 19 日
How can I load to matlab workspace multiple matrices with the same dimension located in individual csv files? They have different file names with the same extension (.csv)
Expected variable in workspace: A 3D matrix.
I have tried something like
Folder = 'C:\My\Folder';';
for k = 1 :100
filename = fullfile(Folder, sprintf('%d.csv', k));
data = readmatrix(filename);
...
end
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 10 月 19 日
@julian gaviria, Does the folder containing the csv files have any other files than the ones to be read?
julian gaviria
julian gaviria 2023 年 10 月 19 日
@Dyuman Joshi, no. there is only 1 sheet per .csv file. All the .csv files contain a 2D matrix with the same dimension

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

採用された回答

Stephen23
Stephen23 2023 年 10 月 19 日
Use DIR:
P = 'C:\My\Folder';
S = dir(fullfile(P,'*.csv'));
for k = 1:numel(S)
F = fullfile(P,S(k).name);
S(k).data = readmatrix(F);
end
All of the imported file data are stored in the structure S. For example, the 2nd file:
S(2).name % filename
S(2).data % file data
  2 件のコメント
julian gaviria
julian gaviria 2023 年 10 月 19 日
Thanks @Stephen23
How can I arrange all the content of "S(2).data" in a 3D array?
Stephen23
Stephen23 2023 年 10 月 19 日
編集済み: Stephen23 2023 年 10 月 19 日
"How can I arrange all the content of "S(2).data" in a 3D array? "
A = cat(3,S.data)
But note that the order of the files will be that returned by DIR, which might not be the order you expect. If you require the filenames in alpha-numerical order then you will have to sort S yourself, e.g. by downloading NATSORTFILES:
S = dir(..);
S = natsortfiles(S);
... etc

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

その他の回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023 年 10 月 19 日
Here is how you can create such a code:
Folder = 'C:\Users\...';
F_Pat = fullfile(Folder, '*.csv');
FILES = dir(F_Pat);
F_Names={FILES.name};
for k = 1 :length(F_Names)
Get_FName = FILES(k).name;
F_FileName=fullfile(FILES(k).folder, Get_FName);
data{k}= readmatrix(F_FileName);
...
end
All the best
  1 件のコメント
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023 年 10 月 19 日
My proposed code works for any file names not necessary file names should be sequential. All collected data in a cell array that can be also altered to store read data as a structure or stacked data of arrays, etc.

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

カテゴリ

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

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by