필터 지우기
필터 지우기

Reading multiple txt files and placing numerical data in a matrix

조회 수: 5 (최근 30일)
Iacopo
Iacopo 2022년 4월 24일
댓글: Iacopo 2022년 4월 26일
Hi all, I'm trying to read multiple file text without the header and pile up their numerical content. I have attached an example txt file.
Here is the basic code I use:
[filename,pathname,d]=uigetfile('*.txt','MultiSelect','on');
filepath=fullpath(pathname,filename);
a=readtable(filepath);
a=table2array(a);
It works for 1 fIle but gives an error for more files selected. And then once I imported correctly multiple files, how do I pile their numerical content? I guess have to insert that in a for cycle. Bear in mind that different files can have different number of columns and rows.
Thanks in advance to anyone who will help me
  댓글 수: 4
Jan
Jan 2022년 4월 25일
"but gives an error for more files selected" - whenever you mention an error in the forum, attach a copy of the complete error message instead of letting the readers guess, what you can see already.
Jeremy Hughes
Jeremy Hughes 2022년 4월 25일
a = readtable(filepath);
a = table2array(a);
Should be equivalent to:
a = readmatrix(filepath)

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2022년 4월 25일
[filename, pathname] = uigetfile('*.txt','MultiSelect','on');
filename = cellstr(filename);
data = [];
for k = 1:numel(filename)
filepath = fullpath(pathname,filename);
tab = readtable(filepath);
data = cat(1, data, table2array(tab));
end
  댓글 수: 5
Jan
Jan 2022년 4월 26일
@lacopo: I've copied "fullpath" from your example in the question. Maybe "fullfile" is meant.
Iacopo
Iacopo 2022년 4월 26일
@Jan you're right, my bad. I modified the piece of code but it doesn't work for more than 1 file. I changed the class of filepath to string to make the readtable function work:
[filename, pathname] = uigetfile('*.txt','MultiSelect','on');
filename = cellstr(filename);
data = [];
for k = 1:numel(filename)
filepath = string(fullfile(pathname,filename));
tab = readtable(filepath);
data = cat(1, data, table2array(tab));
end
If I select 2 files (I just created a copy of my file and selected both the original and the copy) and it gives me the following error:
Error using readtable
"filename" must be a string scalar or character vector.
Error in..
tab = readtable(filepath);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by