2

私は MATLAB を初めて使用するので、これが非常に単純な質問であると確信しています。いくつかの出力データ セットがあり、それぞれにプレフィックス (PT_1 から PT_20 など) が付いています。forループを使用して、各csvファイルの2列目から新しいマトリックスにデータをインポートし、すべてのファイルで一定の時間に合わせたいと思います。

入力ファイルは次のようになります

PT_1.....

time    param 1 param 2 param 3
2/01/2001 23:00 11.449428   3   314.322471
3/01/2001 23:00 11.448935   3   311.683002

PT_2.....

time    param 1 param 2 param 3
2/01/2001 23:00 11.445892   0   296.523937
3/01/2001 23:00 11.445393   0   294.0944

そして、出力を次のようにしたい

time    PT_1    PT_2
2/01/2001 23:00 11.449428   11.445892
3/01/2001 23:00 11.448935   11.445393

これまでのところ、私が持っているコードは

files = 0:1:21;
for i=1:21;
filename = sprintf('WQ_%d.csv', files(i));
origdata = importdata (filename);
end 

ファイル名を正しく認識していることがわかりますが、ループごとにデータを上書きするため、実際にはやりたいことを実行していません。明らかに、コーディングが間違っています。そのための適切なコードを書く方法を理解するのを手伝ってくれる人はいますか? 本当にありがとう!

4

1 に答える 1

0

これを試して:

%# 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
于 2012-12-14T02:33:27.447 に答える