필터 지우기
필터 지우기

To substitute a string in matlab script (.m) file using MATLAB.

조회 수: 4 (최근 30일)
Priya
Priya 2013년 6월 18일
I have a script file (.m) file.
I would like to substitute " dist < 6 dist == 6 " in my matlab code file with "dist < 7 dist == 7" and dist < 8 dist == 8 and so on and save each modified script file as a separate .m file.
  댓글 수: 1
Jan
Jan 2013년 6월 18일
편집: Jan 2013년 6월 18일
What is the your question?
Did you see that the bars disappear in the forum, because they are used as inline code environment?

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2013년 6월 18일
편집: Jan 2013년 6월 18일
The easiest way would be to replace the constant by a variable and use it as input:
function result = YourOriginalFunc(a)
result = (dist < 6 || dist == 6);
function result = YourNewFunc(a, b)
result = (dist < b || dist == b);
Then there is no need for writing a Matlab program which writes (modifies) Matlab programs. Most of all duplicating a function with changing one tiny detail only is a bad programming practice, because this reduces the maintainability.
But if you have really good reasons:
function result = YourOriginalFunc(a)
constant = 6;
result = (dist < constant || dist == constant);
And the modificator:
Str = fileread('YourOriginalfunc.m');
CStr = regexp(Str, '\n', 'split');
index = strncmp(CStr, 'constant =', 10);
for k = 6:10
CStr{index} = sprintf('constant = %d;', k);
FID = fopen(sprintf('NewFunc%d.m', k));
fprintf(FID, '%s\n', CStr{:});
fclose(FID);
end
Btw., dist <= constant is faster than comparing the values twice by < and == .

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Analysis에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by