load the numbers of those lines after character 'X' from text file into matrix
1 view (last 30 days)
Show older comments
Manuel Fuelling
on 31 Mar 2018
Commented: Walter Roberson
on 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 Comments
Accepted Answer
Walter Roberson
on 31 Mar 2018
S = fileread('YourFile.txt');
parts = regexp(regexp(S, '(?<=^\s*x\s*)\S.*$', 'match', 'lineanchors', 'dotexceptnewline'), '\s+', 'split');
data = str2double(vertcat(parts{:}));
2 Comments
Walter Roberson
on 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.
More Answers (0)
See Also
Categories
Find more on Cell Arrays 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!