MATLAB load 2nd column of all files into matrix

5 ビュー (過去 30 日間)
Benjamin Cowen
Benjamin Cowen 2018 年 9 月 19 日
コメント済み: Walter Roberson 2018 年 9 月 20 日
I have a folder with a lot of files of the form: defects_*.txt
Assuming the path to the directory containing these files is C:/Path, how can I load all the files into MATLAB, and create a matrix that contains the 2nd column of each file in the directory.
So basically, I don't care about column 1, but I want to load in the files sequentially, defects_002.txt, defects_005.txt, etc. (no constant increment), and then take the 2nd column from each of these txt files, and paste them as separate columns in a new matrix. So I will have a new matix where column 1 is the 2nd column of defects_0.002.txt, column 2 is the 2nd column of defects_0.005.txt etc. Is this possible?
  2 件のコメント
Christopher Wallace
Christopher Wallace 2018 年 9 月 19 日
What is contained in the defect_*.txt files?
Benjamin Cowen
Benjamin Cowen 2018 年 9 月 19 日
@ChristopherWallace Just 2 columns of data, with 1 header row. I just care about the 2nd column of data, not the header row though

サインインしてコメントする。

回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 9 月 20 日
Reading only the second column can be done in a number of different ways, depending upon the format of the data. One possible way is to use csvread with the r and c parameters both set to 1 -- the r being 1 to skip 1 header row, and the c being 1 to skip 1 column.
  6 件のコメント
Benjamin Cowen
Benjamin Cowen 2018 年 9 月 20 日
hmmm, i get an error
Index exceeds matrix dimensions.
Error in dlmread (line 152)
result = result{1};
Error in csvread (line 48)
m=dlmread(filename, ',', r, c);
Error in defects_v2 (line 7)
thisdata = csvread( filenames{K}, 1, 1); %skip 1 row and 1 column
Walter Roberson
Walter Roberson 2018 年 9 月 20 日
projectdir = 'C:/Path';
dinfo = dir( fullfile(projectdir, 'defects_*.txt') );
filenames = fullfile(projectdir, {dinfo.name});
nfiles = length(filenames);
data = [];
for K = 1 : nfiles
fid = fopen(filenames{K}, 'rt');
thisdata = cell2mat( textscan(fid, '%*f%f', 'HeaderLines', 1) );
fclose(fid);
data(1:length(thisdata), K) = thisdata;
end

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDevelop Apps Using App Designer についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by