首页 > 解决方案 > matlab编辑文本文件,用他们的数字替换

问题描述

我想使用 Matlab 将文本文件中的每个浮点数替换为另一个数字。(假设是原始值的一半)其他数据(整数和字符串)不应更改。我的文本文件的几行(每个变量都在一个新行中):

VERTEX
  8
0
 10
0.000000
 20
110.500000
 42
0.000000
  0
VERTEX
  8
0
 10
0.000000
 20
0.000000
 42
0.000000
  0
VERTEX
  8
0
 10
124.000000
 20
0.000000
 42
0.000000
  0
VERTEX
  8
0
 10
248.000000
 20
0.000000
 42
0.000000
  0
VERTEX
  8
0
 10
248.000000
 20
110.500000
 42
0.000000
  0
VERTEX
  8
0
 10
248.000000
 20
221.000000
 42
0.000000
  0

任何帮助表示赞赏。

标签: matlabedittextscan

解决方案


这是使用fgetl和的解决方案regexp

rid = fopen('test.txt','r');
wid = fopen('test2.txt','w');

while ~feof(rid)    
    s = fgetl(rid); % read a line
    if regexp(s, '\d+\.\d+') % float founded
        fprintf(wid, '42\n'); % wite "another integer"
    else
         fprintf(wid, '%s\n', s); % write original data
    end

end

fclose(rid);
fclose(wid);

推荐阅读