フィルターのクリア

Reading Multiple CSV Files in a Sequence

49 ビュー (過去 30 日間)
Usama Al-Saffar
Usama Al-Saffar 2023 年 2 月 16 日
コメント済み: Usama Al-Saffar 2023 年 2 月 16 日
I wrote a code to read and process 55 csv files.
The first step was to read the data and save it in a cell structure in away that each csv file would be saved in a cell a table:
d=dir('*.csv'); % list all csv files in working directory
n = length(d); % number of files in the directory
tempdata=cell(1,n); % preallocate a cell array to hold results
for i=1:n
tempdata{i}=readtable(d(i).name); % read each file
end
I expected that the 1st. csv file will be stored in tempdata{1,1}, 2nd in cell tempdata{1,2}, etc.. but I noticed that:
tempdata{1,1} = file1.csv
tempdata{1,2} = file10.csv
tempdata{1,3} = file11.csv
.
.
tempdata{1,12} = file2.csv
.
.
How can I change the sequence of saved files so:
tempdata{1,1} = file1.csv
tempdata{1,2} = file2.csv
tempdata{1,3} = file3.csv
.
.
tempdata{1,10} = file10.csv
.
.
tempdata{1,55} = file55.scv
Appreciate the time and efforts that you put to answer this question.

採用された回答

Mathieu NOE
Mathieu NOE 2023 年 2 月 16 日
hello
that's the Achille heel of the native dir command
it will not sort the file names correctly
my example below :
%% read multiple files
P = pwd; % currrent directory
S = dir(fullfile(P,'*.csv')); % get list of files in directory
S = natsortfiles(S); % sort folders / file names into order (https://fr.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort)
for k = 1:numel(S);
F = fullfile(P, fileNames_sorted{k});
S(k).data = csvimport(F); % or READTABLE or whatever.
end
% Take a look in the structure S: it contains all of your file data and the corresponding filenames, just as you require.
% For example, the 2nd filename and its data:
S(2).name
S(2).data
% Accessing and processing this will be much simpler than messing around with dynamically named variables.
  4 件のコメント
Stephen23
Stephen23 2023 年 2 月 16 日
編集済み: Stephen23 2023 年 2 月 16 日
"It looks logical to me but Matlab doesn't recognize the natsortfiles function! "
You need to download the function. File Exchange is a forum for third-party code that is not part of MATLAB.
Open the link that Mathieu NOE gave you. Click on the big blue Download button in the top right corner. Save the ZIP file on your computer. Unzip the zip file into the current MATLAB directory (or on the MATLAB path).
Usama Al-Saffar
Usama Al-Saffar 2023 年 2 月 16 日
Thank you Stephen. I already figure that out and downloaded the function.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by