[英]How do I write a MATLAB code that edits another MATLAB file (.m)?
我有兩個文件,Editor.m和Parameters.m。 我想在Editor.m中編寫一個代碼,該代碼在運行時執行以下任務:
因此,在此過程結束時,Parameters.m將包含dt = 0.6行而不是dt = 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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.