Help us understand the problem. What is going on with this article?

MatlabでCSVファイル読み込み

More than 1 year has passed since last update.

自分用のメモ

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);

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away