load the numbers of those lines after character 'X' from text file into matrix
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2018-3-31
S = fileread('YourFile.txt');
parts = regexp(regexp(S, '(?<=^\s*x\s*)\S.*$', 'match', 'lineanchors', 'dotexceptnewline'), '\s+', 'split');
data = str2double(vertcat(parts{:}));
2 个评论
Walter Roberson
2018-4-1
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!