如何编写编辑另一个MATLAB文件(.m)的MATLAB代码?

时间:2017-02-25 04:44:19

标签: matlab file text-manipulation

我有两个文件,Editor.m和Parameters.m。我想在Editor.m中编写一个代码,运行时执行以下任务:

  • 读取Parameters.m
  • 在其中搜索一行(例如dt = 1)
  • 将其替换为其他内容(例如dt = 0.6)
  • 保存Parameters.m。

因此,在此过程结束时,Parameters.m将包含行dt = 0.6而不是dt = 1,而我没有直接编辑它。

有办法做到这一点吗?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:1)

您可以使用regexprep替换感兴趣的值。

% Read the file contents
fid = fopen('Parameters.m', 'r');
contents = fread(fid, '*char').';
fclose(fid);

% Replace the necessary values
contents = regexprep(contents, '(?<=dt=)\d*\.?\d+', '0.6');

% Save the new string back to the file
fid = fopen('Parameters.m', 'w');
fwrite(fid, contents)
fclose(fid)

如果您可以保证它只会显示为'dt=1',那么您可以使用strrep代替

contents = strrep(contents, 'dt=1', 'dt=0.6');