プログラムによるmファイルの編集方法

24 visualizaciones (últimos 30 días)
MathWorks Support Team
MathWorks Support Team el 6 de Jul. de 2015
Respondida: MathWorks Support Team el 6 de Jul. de 2015
コマンドを組み合わせてmファイルにある変数を検索し、指定の数値に変更する 
というようなことをしたいのですが、MATLABでは既存のmファイルは人の手入力でしか編集できないのでしょうか。 

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 6 de Jul. de 2015
MATLAB の関数を用いての作業となりますと、m ファイルを文字列として読み取って、 
変更を加えたい文字列を探し書き換えるという下記のような作業になります。
%************** function begins ***********************
  function mw_edit_variables(str_old, str_new, filename_old, filename_new)
% Usage:
%     mw_edit_variables('size = 100;', 'size = 1000;', 'sample1.m', 'sample2.m')
%
% sample1.m に含まれる'size = 100;' という記述を 'size = 1000;' と変更した上で、sample2.m に保存しなおします。 
% 'size = 100;' という記述ですが、一行単位で完全一致が必要。 
%
% 1; ファイルを改行を含め一行ずつ読み込み、セル配列として str に保存。 
% 2; 一行ずつ第一入力に一致するかどうかを判断し、一致した場合は第二入力に変更。 
% 3; 2 で一致があった場合は変更を含めた全体のセル配列を m ファイルとして保存。 
 
 
% ファイルを行ごとに改行を含めて読み込み
fid = fopen(filename_old, 'r');
idx = 1;
aLine = fgets(fid);
while ischar(aLine)
    %disp(aLine)
    str(idx) = cellstr(aLine);
    aLine = fgets(fid);
    idx = idx + 1;
end
fclose(fid);
 
% m ファイルの行数
lineNumber = length(str);
 
% 必要な変更を加えます(完全一致が必要)
flag = false;
for i = 1:lineNumber
    if all(strcmpi(str{i}, str_old))
        str{i} = str_new;
        message = ['L', num2str(i), ': ', str_old, ' is modified to ', str_new];
        disp(message);
        flag = true;
    end
end
 
% 変更がある場合にファイル作成
if flag
    % 変更後のファイル保存
    fid = fopen(filename_new, 'w');
    for i = 1:lineNumber
        fprintf(fid, '%s\n', str{i});
    end
    fclose(fid);
    
else
    % 変更がない場合に出力
    disp('no change made and a new file is not created.');
end
 
end
  %************** function ends ***********************
また、Windows 7 の built-in 関数のpowershell でも同様の作業ができます。
! (感嘆符) を用いてMATLAB のコマンドウィンドウ上から、もしくはスクリプトでも呼び出せます。 
!powershell -Command "(gc -Encoding Default sample1.m) -replace '= 100','= 1000' | Out-File -Encoding default sample2.m" 
powershell.exe はこちらの環境ですと、C:\WINDOWS\system32\WindowsPowerShell\v1.0 にございます。PATH をご確認ください。 
-Command "... " ; " " の間に実行したいコマンドを入力します 
(gc sample.m) で sample.m を読み込みます。(gc は Get-Content command の略) 
-replace '= 5', '= 100' ; '= 5' を '= 100' に書き換えます。 
| Out-File sample2.m ;書き換えた結果を sample2.m に。上書きの場合は同じ名前を指定してください。 
日本語の文字が含まれる場合にはエンコーディングに注意する必要があります。 

Más respuestas (0)

Categorías

Más información sobre スクリプト en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!