How can i keep my variables after running the function?

113 ビュー (過去 30 日間)
Niloufar Hojat
Niloufar Hojat 2019 年 7 月 15 日
編集済み: Adam Danz 2019 年 12 月 2 日
I have written a function that does some data anlayising on a table and then I have another function that uses that analysed data and does further analyses on it. The two functions used to be one but I have separated them. Is it possible to keep the variables once a function has run as currently all the variables in the function are cleared after running it.
Many thanks,
Nima
  2 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 15 日
Variabes from function file or main script?
Stephen23
Stephen23 2019 年 7 月 15 日
By far the simplest, neatest, and most efficient way to pass variables from one workspace to another is to pass them as input/output variables. Have you tried doing that?

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

採用された回答

Adam Danz
Adam Danz 2019 年 7 月 15 日
編集済み: Adam Danz 2019 年 12 月 2 日
" Is it possible to keep the variables once a function has run "
Yes.
Add outputs to your function if variables are immediately needed in other functions or scripts.
Otherwise, you can save any (or all) variables within a function by calling save(filename,variables) at the end of the function (for troubleshooting purposes).
If you are running a script, any variables within the script are already available in the caller workspace.
  3 件のコメント
Guillaume
Guillaume 2019 年 7 月 17 日
編集済み: Guillaume 2019 年 7 月 17 日
"I hesitate to suggest save, as it encourages saving the entire workspace and then poofing them back with load."
In addition round-tripping through a file is never going to be fast. It's certainly not the way to go.
If the two functions must share the same entire workspace then there's a fundamental design issue. If it's only a few variables, then inputs and outputs are definitiively the way to go. If it's the whole workspace then i'd question if the code should have been split.
Adam Danz
Adam Danz 2019 年 7 月 17 日
編集済み: Adam Danz 2019 年 7 月 17 日
I added a caveat to the save() suggestion. Sometimes this approach is useful when troubleshooting a function that takes a long time to run and breaks only seldomly. As far as passing variables between functions, the save/load approach is clearly a bad idea.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by