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.

 采纳的回答

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 Exchange 中查找有关 Large Files and Big Data 的更多信息

产品

版本

R2021b

标签

Community Treasure Hunt

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

Start Hunting!

Translated by