How do I import a file containing both numbers and strings
Show older comments
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?
Accepted Answer
More Answers (2)
TADA
on 22 Nov 2018
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
on 22 Nov 2018
0 votes
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.
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!