load the numbers of those lines after character 'X' from text file into matrix
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Manuel Fuelling
am 31 Mär. 2018
Kommentiert: Walter Roberson
am 1 Apr. 2018
i have a text file which looks like this:
Bla 1 2 3
Bla 1 2 3
x 100.0 200.5 100.6
x 55 66 77
k 45 45 45
k 55 55 55
i wan to load the values which come after x into a matrix. in this case 2x3 matrix. The code should look for the x's in the file and extract the three numbers after it for every line, which starts with a 'x'. how to implement this?
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 31 Mär. 2018
S = fileread('YourFile.txt');
parts = regexp(regexp(S, '(?<=^\s*x\s*)\S.*$', 'match', 'lineanchors', 'dotexceptnewline'), '\s+', 'split');
data = str2double(vertcat(parts{:}));
2 Kommentare
Walter Roberson
am 1 Apr. 2018
In the assignment to parts change the x to k
The code reads the file as one continuous character vector. Then it uses regexp to look for lines that start with x (possibly with space before) and extracts to the end of line without the x. Then it splits each of the ends at blanks. This gets you to a cell array that has one entry per detected line, and each entry has been split into a cell array of character vectors, one per field.
Then the contents of the outer cell array are extracted and the results slammed together into an array. You now have a 2d cell array, lines by fields, instead of nested cells.
2d cell array is then passed to the routine that converts character vectors to numeric form, which happens to also work on cell array of such characters. The result is a 2d array of numbers.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!