フィルターのクリア

clearing a persistent variable makes it no longer persistent

2 ビュー (過去 30 日間)
CM
CM 2024 年 5 月 22 日
回答済み: CM 2024 年 5 月 22 日
This is something that keeps catching me out. I do not think it is explicitly documented anywhere, though it could be implied in the matlab instructions to clear persistent variables by clearing the function.
If you clear a persistent variable using clear variablename from within the function, it ceases to be persistent.
Something like this would be handy to have as there are situations where I want to clear some, but not all persistent variables in a function. Clear allows you to do it all in one line. The alternative is to set them all to [], which is a bit more verbose.
  1 件のコメント
Abhishek Kumar Singh
Abhishek Kumar Singh 2024 年 5 月 22 日
Hi @CM, I think it is mentioned in documentation of persistent that clearing the function that declares the variable clears the persistent variable. You can refer to the Tips section of this page: https://www.mathworks.com/help/matlab/ref/persistent.html#:~:text=To%20clear%20a%20persistent%20variable%2C%20use%20clear%20with%20the%20name%20of%20the%20function%20that%20declares%20the%20variable.%20For%20example%2C%20clear%20myFun
When the clear command is used within a function to clear a variable, it removes the variable from the workspace entirely. This means that not only does it cease to be persistent, but it also gets cleared from memory.:
function foo()
persistent counter;
counter = 43;
% Display
disp(['Counter value: ' num2str(counter)]);
disp("Before clearing counter..")
disp(whos('counter'))
% Clear the persistent variable (ceases to be exists)
clear counter;
disp("After clearing counter..");
disp(whos('counter'));
end
foo()
Counter value: 43 Before clearing counter.. name: 'counter' size: [1 1] bytes: 8 class: 'double' global: 0 sparse: 0 complex: 0 nesting: [1x1 struct] persistent: 1 After clearing counter..
Is there any additional information you're seeking?

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

採用された回答

埃博拉酱
埃博拉酱 2024 年 5 月 22 日
You can use deal to set multiple variables to the same value at once (such as an empty value, in your case). Using clear in a function is very unusual and is not the right choice in most cases.

その他の回答 (1 件)

CM
CM 2024 年 5 月 22 日
Thanks 埃博拉酱 and Abhishek. Deal looks like what I was after.

カテゴリ

Help Center および File ExchangeWhos についてさらに検索

製品


リリース

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by