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

10 ビュー (過去 30 日間)
Adriano Filippo Inno
Adriano Filippo Inno 2017 年 9 月 18 日
編集済み: Stephen23 2017 年 9 月 19 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by