I have a text file (attached). I am trying to extract a specific part (Nodes part) starting by reading the header (nodal.coordinates) then extract the following four columns (node name, x, y and z). I am trying textscan ad cell2mat functions but I got an empty matrix. Many thanks in advance.

 採用された回答

Stephen23
Stephen23 2022 年 2 月 7 日
編集済み: Stephen23 2022 年 2 月 7 日

0 投票

Method one: TEXTSCAN:
fmt = '%s%f%f%f';
opt = {'MultipleDelimsAsOne',true, 'CollectOutput',true, 'HeaderLines',1};
fid = fopen('sampleQ.txt','rt');
while ~feof(fid) && ~strcmp(fgetl(fid),'nodal.coordinates')
end
out = textscan(fid,fmt,opt{:});
fclose(fid);
out{:}
ans = 8×1 cell array
{'n111' } {'n111-y1'} {'n111-y2'} {'n111-y3'} {'n121' } {'n121-x1'} {'n121-x2'} {'#' }
ans = 7×3
0 0 0 0 450 0 0 1500 0 0 2550 0 0 3000 0 600 3000 0 2000 3000 0
Method two: REGEXP:
str = fileread('sampleQ.txt');
str = regexp(str,'(?<=nodal\.coordinates\s+)[^#]+','match','once');
tkn = regexp(str,'^\s*(\S+)\s+(\d\S+)\s+(\d\S+)\s+(\d\S+)','tokens','lineanchors');
tkn = vertcat(tkn{:})
tkn = 7×4 cell array
{'n111' } {'0.' } {'0.' } {'0.'} {'n111-y1'} {'0.' } {'450.' } {'0.'} {'n111-y2'} {'0.' } {'1500.'} {'0.'} {'n111-y3'} {'0.' } {'2550.'} {'0.'} {'n121' } {'0.' } {'3000.'} {'0.'} {'n121-x1'} {'600.' } {'3000.'} {'0.'} {'n121-x2'} {'2000.'} {'3000.'} {'0.'}
mat = str2double(tkn(:,2:end))
mat = 7×3
0 0 0 0 450 0 0 1500 0 0 2550 0 0 3000 0 600 3000 0 2000 3000 0

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Import and Export についてさらに検索

製品

リリース

R2021b

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by