第一步是读取数据。我假设您的文件内容如下所示:
-- comment
34*0.00 0.454 0.223
0.544 5*4.866
对于该格式,您可以像这样使用textscan:
fid = fopen('data.txt');
data = textscan(fid, '%s', 'CommentStyle', '--');
fclose(fid);
data = data{1};
而data 在显示时将如下所示:
data =
5×1 cell array
'34*0.00'
'0.454'
'0.223'
'0.544'
'5*4.866'
现在,您可以尝试几种不同的方法将其转换为所需格式的数字数据。一种(可能是可怕的)方法是像这样使用regexprep:
>> data = regexprep(data, '([\d\.]+)\*([\d\.]+)', ...
'${repmat([$2 blanks(1)], 1, str2num($1))}')
data =
5×1 cell array
'0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0…'
'0.454'
'0.223'
'0.544'
'4.866 4.866 4.866 4.866 4.866 '
如您所见,它会根据需要复制每个字符串。现在,我们可以使用cellfun 和str2num 将元胞数组的每个元胞转换为数值并将它们连接在一起:
>> num = cellfun(@str2num, data, 'UniformOutput', false);
>> num = [num{:}]
num =
Columns 1 through 14
0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 15 through 28
0 0 0 0 0 0 0 0 0 0 0 0 0 0
Columns 29 through 42
0 0 0 0 0 0 0.4540 0.2230 0.5440 4.8660 4.8660 4.8660 4.8660 4.8660