How to skip (variable) white space using textread

If I have a text file with different amount of white spaces in between the text and numbers, how can I get "textread" to ignore the (variable) whitespaces? For example see test(002).txt
Eventually I want to make a table with these variables to make plots and do statistics etc.

 채택된 답변

Jeff Miller
Jeff Miller 2018년 3월 30일

0 개 추천

GetNumsInAsciiFile on File Exchange will probably do what you want: https://au.mathworks.com/matlabcentral/fileexchange/66692-getnumsinasciifile-sfname-

댓글 수: 2

To bad I have R2015b..
The code in that submission does not use anything newer than R2013a.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2018년 3월 30일

1 개 추천

I suggest using
readtable()
I do not recommend textread() in any release from R14 onwards. (I do not mean R2014* -- I mean R14, MATLAB 7.0, release in June 2004.)

댓글 수: 7

If I try readtable, I get the error "input must be a row vector of characters". Even if I make a txt or dat file with the text from te example I get the same error.
filename = 'testfile.dat';
fileID = fopen(filename)
T = readtable(fileID)
This is the text in the file:
Lastname,Gender,Age
Smith,M,38
Johnson,M,43
I think it has to do with fopen. Since the fileID is -1, and I read this is when fopen cannot open the file..
You do not readtable() a file identifier, you readtable() a file name.
T = readtable(filename);
However if you are getting a fileID of -1 then it probably cannot find the file, and you might need to specify the directory name as well. For example,
[filename, filepath] = uigetfile('*.dat', 'Choose a data file');
if ~ischar(filename)
return; %user cancel
end
filename = fullfile(filepath, filename);
T = readtable(filename);
Fopen now works correct, thanks!
The initial problem however is still there. I don't see how I can solve the problem with the inconsistent white spaces between the variables/numbers. The Delimiter is variable since the amount of white spaces differ, so cannot use this. If I use Format he reads the whole row as one string, in stead of one string and 4 numbers.
In my text file the first row contains 5 different words, with variables white spaces amounts in between. And the upcoming rows contain one word, followed by 4 numbers, also with variable white space amounts in between.
Just found the MultipleDelimsAsOne! Thanks again.
readtable() will take care of this for you.
If you use textscan() then use a format of '%s%s%s%s', and do not bother using MultipleDelimsAsOne . Any amount of whitespace on input is skipped before a %s or numeric format item is processed.

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

카테고리

도움말 센터File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by