Only clear the variables in for loop

6 ビュー (過去 30 日間)
Catherine Fung
Catherine Fung 2018 年 7 月 11 日
コメント済み: Guillaume 2018 年 7 月 11 日
Hi guys, I am wondering if there is quick way to clear the variables just in the for loop but not the variables outside the for loop? I know I can use
clearvars
clearvars -except
However, I have as much variables in the for loop as those outside the loop; around 30 different variables each. Is there a way that I don't have to type all of them out?
Thanks!

採用された回答

Jan
Jan 2018 年 7 月 11 日
It is rarely useful to clear variables in the workspace. In many cases this decreases the speed. Prefer a proper pre-allocation, such that clearing is not required anymore.
30 Variables are a lot for a loop. Remember that a high code complexity reduces the readability and maintainability. The need to clear variables might be a secure signal, that the complexity has grown over a certain limit. A solution would be to move the body of the loop into an extra function. Then the smaller piece of code is easier to test, to modify, to debug and to maintain, and in addition the workspace is kept clean automatically.
  2 件のコメント
Catherine Fung
Catherine Fung 2018 年 7 月 11 日
Creating a separate function for that particular loop is a great idea. Thanks!
Guillaume
Guillaume 2018 年 7 月 11 日
Yes, as Jan says, move the calculations performed inside the loop into their own functions. That way, there will be nothing to clear and your code will be a lot more readable.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by