How to read and process a text file?

조회 수: 2 (최근 30일)
Bertilla Raque
Bertilla Raque 2019년 12월 15일
댓글: Bertilla Raque 2019년 12월 20일
I have attached a sample text file. As yOu can see the comment lines starting with $ must be ommited and the values alone must be read and assigned as variables. For the 'ID' set each column must be named separately like a1 to a4 for the second column and b1 to b4 for the third and so on. Similarly the 'NEXT' set must also be named as each column separately. Please help......
  댓글 수: 2
Walter Roberson
Walter Roberson 2019년 12월 15일
Don't do that. Put all of the data into the same variable. Use a structure with dynamic field names for the main variable and use vectors instead of a1 a2 and so on.
Bertilla Raque
Bertilla Raque 2019년 12월 15일
Thank you for your suggestion....I need to perform calculations furthur with the stored variables... and i dont kno how to read the ID set separately and NEXT set separately. Textscan only reads once and then throws a error... how to read the text file from NEXT directly?

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2019년 12월 16일
S = fileread('sample.txt');
S = regexprep(S, {'^\$.*?\n', '\r'}, {'', ''}, 'lineanchors');
all_ids = string(regexp(S, '^\S*', 'match', 'lineanchors'));
noids = regexprep(S, '^\S*\s*', '', 'lineanchors');
mask = all_ids(1:end-1) ~= all_ids(2:end);
stops = find([mask true]);
eol_pos = regexp(noids, '.$', 'lineanchors');
block_lengths = diff([0, eol_pos(stops)]);
blocks_text = mat2cell(noids, 1, block_lengths);
ids = all_ids(stops);
values = cellfun(@(B) cell2mat(textscan(B, '', 'CollectOutput', true)), blocks', 'uniform', 0);
At this point, ids contains a string vector of the names such as NEXT, and values is a cell array of numeric arrays, with each entry containing the numeric data corresponding.
  댓글 수: 9
Walter Roberson
Walter Roberson 2019년 12월 20일
Again, why do you need to name the columns when you can just index instead?
Bertilla Raque
Bertilla Raque 2019년 12월 20일
so that I can use in them in furthur calculations in a loop. I think I was having problems with the loop because of the scalar problem I'll try indexing.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품


릴리스

R2012b

Community Treasure Hunt

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

Start Hunting!

Translated by