How to clear workspace from a function?
古いコメントを表示
Hi,
I want to create a function that will perform some maintenance operations at the beginning of the script. For example, this function takes a few arguments that will lead to specific initialisations of paths and variables, and above all, clear the workspace from the previous run.
I want to put it in a specific function as the job requires dozens of lines which are quite irrelevant in the work. And I want my "main' script to be as short, readible and high-level as possible.
Below only the first lines of the function.
function init_step(varargin)
clearvars -except varargin
close all
clc
However if I do 2 consecutive runs, it does not clear the workspace. If I want to, I need to explicitely write the "clear" command in the main script, which I try to avoid.
Is there any way to do it?
Thanks in advance.
2 件のコメント
The simple solution would be to make the "specific function" a script, then when you run it, it will clear the worksapce of your main script. But.... using scripts and needing to clear workspaces is a strong indication that you should to refactor your code:
Louis Tomczyk
2023 年 1 月 17 日
採用された回答
その他の回答 (2 件)
Hiro Yoshino
2023 年 1 月 16 日
1 投票
One way you can delete variables from the Function Workspace is that you make your variables "global" so you can have access from anywhere.
Louis Tomczyk
2023 年 1 月 17 日
2 件のコメント
Bora Eryilmaz
2023 年 1 月 17 日
編集済み: Bora Eryilmaz
2023 年 1 月 17 日
You cannot clear the variables in the main function by calling clear inside another function (init_step).
You can probably describe why you are trying to do something like this as this is a highly unusual thing to try to do. Then someone can probably offer a better workflow/solution. For example, you can make init_step return the initial values of the variables that you are trying to clear. Something like this:
[a, b, c] = init_step(...)
Louis Tomczyk
2023 年 1 月 17 日
カテゴリ
ヘルプ センター および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!