Date: Sep 24, 2013 11:38 AM
Author: Steven Lord
Subject: Re: "clear -except" and "clearvar -except"

"Senthil nathan" <> wrote in message
> Hi all, I would like to discus about the result of "clearvars -except" and
> "clear -except" with others.
> When I tried to run a program in loop , I have to clear all variables,
> workspace etc except the running variable , which is used as the only one
> parameter ( input ), to continue to the next iteration. As the program is
> very lengthy , I herewith explain the situation with a simple loop.

Why not convert the body of your FOR loop into a function? Functions operate
in their own workspace, meaning that (ignoring nested functions, GLOBAL,
LOAD, EVALIN, etc.) the only variables that enter the function workspace are
the input arguments with which you call it and the only variables that exit
are the output arguments. This control means that variables created inside a
function generally don't affect (ignoring PERSISTENT and the things I
already said I was ignoring) later calls to that function.

> In the following program I have to keep the value of the variable i .
> Herewith I give three variations of the program. But the when I try to
> keep the value of the variable i , matlab keep the value of the variable j
> and erases the variable i and viz versa. [Note that "clearvars -except"
> command works well as I expect. The only problem is "clearvars" clears
> only variables and not the entire workspace.
> %% ----------------------------First version of the
> program---------------------------------------
> for i=1:10
> j=i+1;
> clearvars -except i % This line works as I expect
> end
> whos
> The output is :-
> Name Size Bytes Class Attributes
> i 1x1 8 double

Yes. CLEARVARS accepts the flag input -except.

> %% ----------------------------Second version of the
> program---------------------------------------
> clc
> clear
> for i=1:10
> j=i+1;
> clear -except i % This line is NOT working as I expect.
> end
> whose
> The output is :-
> Name Size Bytes Class Attributes
> j 1x1 8 double You may be appreciated if you
> run the above programs and give your suggestions

CLEAR does NOT list a flag input named -except in its calling syntax.

Steve Lord
To contact Technical Support use the Contact Us link on