How can I overwrite a variable saved in a script that I have to loop with a different value?

조회 수: 8 (최근 30일)
Try to make that simple:
a = [10 20 30 40];
for i = 1:4
run('blabla.m') % but inside the script: a = 18
end
Is possible to force the variable 'a' to be equal at a(i) ?

답변 (1개)

James Tursa
James Tursa 2017년 9월 18일
편집: James Tursa 2017년 9월 18일
Edit the script file blabla.m, and comment out the a = 18 line:
% a = 18;
Also, make sure the script file blabla.m does not clear variables.
Then in your driver code:
A = [10 20 30 40];
for i = 1:4
a = A(i);
run('blabla.m')
end
You might also consider turning the blabla.m script file into a function so that you could just pass in the A(i) value directly as an argument.
  댓글 수: 3
James Tursa
James Tursa 2017년 9월 18일
편집: James Tursa 2017년 9월 18일
No. If the script file sets "a = 18" directly, then it will override anything you do to try and set it to something else ahead of time. The remedy is to modify the script file (or the functions it calls that use "a") in some way.
If, however, you are willing to set breakpoints in your script file after the "a = 18" line, then you could manually set "a" to something else when the script file pauses in the debugger. But I would imagine that would be a pain to do every time you ran the script file.
Stephen23
Stephen23 2017년 9월 19일
편집: Stephen23 2017년 9월 19일
@Adriano Filippo Inno: this is why we advise beginner to write functions rather than scripts. Then they end up wasting less time trying to create work-arounds for pointless problems like that one you have now. Expert MATLAB users do not write scripts with hard-coded values that call lots of other scripts, instead they write functions that encapsulate some functionality and don't waste their time like you are now.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by