How do I import a file containing both numbers and strings
이전 댓글 표시
I've looked around and found multiple posts regarding this issue, however, none of them really helped me with this problem.
I'm trying to import a text file cointaining a square matrix, defined by the user, that contains values and the string X like, for example, this one:
17.01 24.02 1.03 8.04
23.06 5.07 7.08 14.09
4.01 X 13.03 20.04
10.06 12.07 19.08 21.09
11.01 18.02 25.03 2.04
I've tried using importdata but when it reaches the X, the rest of the line gets replaced by NaN and the lines underneath get ignored. This is what happens:
17.0100 24.0200 1.0300 8.0400
23.0600 5.0700 7.0800 14.0900
4.0100 NaN NaN NaN
Since the matrix is given by the user (randomly), its size and the 'X' positions will always be different. Knowing that the matrixes are always square, what can I do to solve this?
채택된 답변
추가 답변 (2개)
TADA
2018년 11월 22일
txt = fileread('blah.dat');
lines = strsplit(txt, newline);
x = regexp(lines, '[^ ]+', 'match');
items = cat(1,x{:});
A = str2double(items);
your X would now be represented by NaN in matrix A
dpb
2018년 11월 22일
0 개 추천
If you're going to read in text in random locations, unless you can determine or require the user to tell you where those locations are, the only alternative will be to read the whole array as cellstr array and then figure out after the fact "who's who in the zoo" as far as which locations are/aren't numeric.
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!