フィルターのクリア

Keep a variable in workspace when calling a function

31 ビュー (過去 30 日間)
Dingguo Lu
Dingguo Lu 2011 年 11 月 12 日
回答済み: Andrej Sternin 2020 年 4 月 11 日
My question is how to keep a variable in a called function into the workspace.
I was told the code can be written using persistent memory inside the function.
As known, when calling a function, all the variables will be cleared after the function is called, i.e., no variables will appear in workspace.
Can anybody tell me how to work on it.
Thanks in advance.
  1 件のコメント
Sven
Sven 2011 年 11 月 12 日
Yes, there is a thing called a "persistent variable".
Is this what you would like to use?

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

回答 (3 件)

Andrej Sternin
Andrej Sternin 2020 年 4 月 11 日
https://de.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html

the cyclist
the cyclist 2011 年 11 月 12 日
I don't perfectly understand what you mean, but I can think of three possibilities that might help you:
  • Send the variable as output
  • Use a global variable
  • Use the assignin() function
You should easily be able to find information about all of these in the documentation.

Jonathan
Jonathan 2011 年 11 月 12 日
The code below uses a persistent variable. The first time the function is run, the variable is given the value [] (the empty matrix).
function out = testPersistent()
persistent x
if isempty(x)
x = 1;
else
x = x + 1;
end
out = x;
end
When I run the function several times, this is what the output looks like.
>> testPersistent()
ans = 1
>> testPersistent()
ans = 2
>> testPersistent()
ans = 3
I hope this helps.

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by