複数のcsvファイルを一度に読み込みたい

44 views (last 30 days)
yuta
yuta on 23 Mar 2022
Commented: yuta on 26 Mar 2022
同じフォルダに1stcap01.csv, 1stcap02.csv,1stcap03.csv . . . と複数のファイルがある時に
以下の処理を用いて、それぞれのデータの読み込みを同時に行いたいです。
1つ1つ処理をすれば良いのですが、csvファイルの数が多いため、何か良い方法がありましたらご教示いただけると幸いです。
data = readmatrix('1stcap01.csv');
idx = isnan(data(:,2));
idx_or =[0;diff(idx)]<0|[diff(idx);0]>0;
num = find(idx_or);
if mod(length(num),2)
num = [num;height(idx_or)];
end
for ii = 1:length(num)/2
A{ii,1} = data(num(2*ii-1):num(2*ii),:);
end
B = cellfun(@(x) rmmissing(x,2),A,'UniformOutput',false);
cellfun(@size,B,'UniformOutput',false)
よろしくお願いいたします。

Accepted Answer

Hernia Baby
Hernia Baby on 23 Mar 2022
関数にして繰り返し操作し、連結させましょう。
■フルパス取得
clc,clear;
Pathlists = dir("*.csv");
Mylists = (struct2cell(Pathlists))';
Mylists = string(Mylists(:,1:2));
MyPath = fullfile(Mylists(:,2),Mylists(:,1))
MyPath = 4×1 string array
"/users/mss.system.wqe8pX/Sample (1).csv" "/users/mss.system.wqe8pX/Sample (2).csv" "/users/mss.system.wqe8pX/Sample (3).csv" "/users/mss.system.wqe8pX/Sample (4).csv"
中身を少しだけ変えたものを入れています
■関数の使用
MyPreprocessという関数を作り、縦に連結させています
MyCell = [];
for jj = 1:height(MyPath)
MyCell = [MyCell;MyPreprocess(MyPath(jj))];
end
MyCell
MyCell = 8×1 cell array
{20×11 double} {20×11 double} {20×11 double} {20×11 double} {20×11 double} {20×11 double} {20×32 double} {10×8 double}
どこでどうやって区切ったかわからない場合は以下のようにするといいと思います
MyCell = [];
for jj = 1:height(MyPath)
MyCell = [MyCell;{MyPath(jj)};MyPreprocess(MyPath(jj))];
end
MyCell
MyCell = 12×1 cell array
{["/users/mss.system.wqe8pX/Sample (1).csv"]} {20×11 double } {["/users/mss.system.wqe8pX/Sample (2).csv"]} {20×11 double } {20×11 double } {["/users/mss.system.wqe8pX/Sample (3).csv"]} {20×11 double } {["/users/mss.system.wqe8pX/Sample (4).csv"]} {20×11 double } {20×11 double } {20×32 double } {10×8 double }
■以下関数
今回は同じスクリプト内に以下の用にコード化しました
パスからcsvを読み込んで処理しているだけです
function B = MyPreprocess(path)
data = readmatrix(path);
idx = isnan(data(:,2));
idx_or =[0;diff(idx)]<0|[diff(idx);0]>0;
num = find(idx_or);
if mod(length(num),2)
num = [num;height(idx_or)];
end
for ii = 1:length(num)/2
A{ii,1} = data(num(2*ii-1):num(2*ii),:);
end
B = cellfun(@(x) rmmissing(x,2),A,'UniformOutput',false);
end
  1 Comment
yuta
yuta on 26 Mar 2022
返信が遅れて申し訳ありません。
解決いたしました。
複数回にわたりご対応いただきありがとうございました!

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB 入門 in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!