Search code examples
matlabfiletext-manipulation

How do I write a MATLAB code that edits another MATLAB file (.m)?


I have two files, Editor.m and Parameters.m. I want to write a code in Editor.m that when run does the following task:

  • reads Parameters.m
  • searches for a line in it (e.g. dt=1)
  • replaces it with something else (e.g. dt=0.6)
  • saves Parameters.m.

So, at the end of this process, Parameters.m will contain the line dt=0.6 instead of dt=1, without me having edited it directly.

Is there a way to do this? If so, how?


Solution

  • You can use regexprep to replace the value of interest.

    % 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)
    

    If you can guarantee that it will only ever appear as 'dt=1', then you can use strrep instead

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