Change empty string to "NaS" when reading from a file

I want to read from a text file which has certain blank string cells in it. However, the character data isn't a numeric value, so I cannot use 'emptyvalue',NaN Is there a similar way for textread to fill blank cells for string with 'NaS'(Not a String)? I have tried many methods to overcome this but I am still lost. I have read that using "%[^ ]" can ignore characters in the box but I get an error when using it. Am I using it the wrong way?
inFile = 'filepath';
% Extracting data from the input file
[a,b,c,d] = textread(inFile,'%*d %*s %*s %*s %*s %*s %*s %*s %f %f %*d %[^ ] %s','headerlines',2,'delimiter','\t','emptyvalue', NaN);

댓글 수: 1

Stephen23
Stephen23 2018년 9월 27일
편집: Stephen23 2018년 9월 27일
Note: at the very top of the textread help page it states:
" textread is not recommended. Use textscan instead."
I would recommend following the advice in the MATLAB documentation.
"Am I using it the wrong way?"
You are using very outdated textread, instead of the reccomended textscan.
"However, I don't see any difference in what textscan would do as it still reads the data like textread."
You might not see any difference, but clearly the makers of MATLAB do, because they specifically advise against using it. Legacy functions, like textread, are not recommended for new code or projects.

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

답변 (1개)

Bish Erbas
Bish Erbas 2018년 9월 27일
You can import all data as into a string cell array A and then perform all required conversions.
f = fopen('file.txt');
A = textscan(f,'%s %s %s %s %s %s %s %s %s %s %s %s %s','headerlines',2,'delimiter','\t');
fclose(f);

댓글 수: 3

Madlab
Madlab 2018년 9월 27일
편집: Madlab 2018년 9월 27일
Thank you very much for the input. However, I don't see any difference in what textscan would do as it still reads the data like textread. Furthermore, I find it more cumbersome as I would have to extract out the respective data I want from the cell array of A. Not all the data inside the file is string too. There are some that are numbers.
It is only for some data set that there are blanks, and for those I would prefer to set it as "NaS" similar to the way of 'emptyvalue',NaN
"Not all the data inside the file is string too. There are some that are numbers."
So change the format string.
Stephen is right. Mine is just a simple example. Replace %s with %d for the columns contain numeric values if you want to save a few lines of post-processing after the import.

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

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

2018년 9월 27일

댓글:

2018년 9월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by