LoginSignup
1
3

More than 5 years have passed since last update.

MatlabでCSVファイル読み込み

Last updated at Posted at 2018-02-14

自分用のメモ

1行目はヘッダ。

入力ファイル

h1,h2,h3,h4,h5,h6,h7
1,2,3,4,5,6,7
1,2,3,,,,
1,2,3,4,5,6,7
1,2,3,4,5,6,7
1,2,3,,,,
1,2,3,4,5,6,7
1,2,3,,,,

textscan版

filepath = 'C:\data.csv';
fileId = fopen(filepath, 'r');
% 3列目以降を無視
data = textscan(fileId, '%f%f%*[^\n]', 'delimiter', ',', 'headerLines', 1 );
fclose(fileId);
% 戻り値は1×2のcell配列になる
data 

readtable版

filepath = 'C:\data.csv';
data =  readtable(filepath, 'delimiter', ',');
% 戻り値は8×9のテーブルになる。勝手にヘッダも認識される。
data
% 簡単に全列読み込めたデータだけに絞り込みできる
truedata = rmmissing(data);
truedata

fgetl版

h1 = [];
h2 = [];            
fileId = fopen(filepath, 'r');
row = fgetl(fileId); % ヘッダ空読み
row = fgetl(fileId);
while ischar(row)
  columns = strsplit(row, ',');
  if length(columns) > 4
    % ほかにもっとよい書き方があるのだろうか
    h1 = [h1; str2double(columns{1})];
    h2 = [h2; str2double(columns{2})];
  end
  row = fgetl(fileId);
end
fclose(fileId);

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3