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?

採用された回答

Walter Roberson
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 件のコメント
Manuel Fuelling
Manuel Fuelling 2018 年 4 月 1 日
編集済み: Manuel Fuelling 2018 年 4 月 1 日
Thanks! Could you explain the code? Where do i change the code, if i want to load the numbers after k?
Walter Roberson
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 ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by