필터 지우기
필터 지우기

load the numbers of those lines after character 'X' from text file into matrix

조회 수: 3 (최근 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 CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by