これを試して:
%# Set the number of csv files
DirectoryPath = 'FullDirectoryPathHereWithTrailingSlash';
NumFile = 2;
%# Open the first file and get the first column (the date column)
File1Path = [DirectoryPath, 'PT_1.csv'];
fid1 = fopen(File1Path, 'r');
Date = textscan(fid1, '%s %*[^\n]', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid1);
%Convert dates to matlab date numbers and get number of rows
Date = datenum(Date{1, 1}, 'dd/mm/yyyy');
T = size(Date, 1);
%# Preallocate a matrix to hold all the data, and add the date column
D = [Date, NaN(T, NumFile)];
%# Loop over the csv files, get the second column and add it to the data matrix
for n = 1:NumFile
%# Get the current file name
CurFilePath = [DirectoryPath, 'PT_', num2str(n), '.csv'];
%# Open the current file for reading and scan in the second colum using numerical format
fid1 = fopen(CurFilePath, 'r');
CurData = textscan(fid1, '%*s %f %*[^\n]', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid1);
%Add the current data to the cell array
D(:, n+1) = CurData{1, 1};
end
私が提供したコメントを使用して、コードが一目瞭然であることを願っています。少しトリッキーなのは、textscan
関数で使用した書式文字列です。簡単な説明は次のとおりです。
1)'%s %*[^\n]'
は次のように述べています。文字列形式の最初の列を取得し (ie %s
)、残りの列をすべてスキップします (ie %*[^\n]
)。
2)'%*s %f %*[^\n]'
は次のように述べています。文字列形式の最初の列をスキップし (つまり%*s
)、浮動小数点数である 2 番目の列を取得し (つまり%f
)、残りのすべての列をスキップします (つまり%*[^\n]
)。
更新:コードを更新して、csv ファイルが存在するディレクトリを指定できる変数を上部に含めました (現在のディレクトリではない場合)。テキスト FullDirectoryPathHereWithTrailingSlash を適切なパス ( /home/username/Documents/
Linux やC:\Windows\Blah\
Windows など) に置き換えるだけです。
このコードを 2 つのテスト csv ファイルでテストしたPT_1.csv
ところPT_2.csv
、次のように表示されます。
time, param 1, param 2, param 3
2/01/2001 23:00, 11, 3, 314.322471
3/01/2001 23:00, 12, 3, 311.683002
と
time, param 1, param 2, param 3
2/01/2001 23:00, 13, 0, 296.523937
3/01/2001 23:00, 14, 0, 294.0944
結果?
>> D
D =
730853 11 13
730854 12 14