Why Does "clear all" Impact Prior Commands in a Script?
Show older comments
Here is the example code. If I comment the "clear all" line in Section 2 the ouput of fplot() in Section 1 comes out fine with no warnings. It's almost like the execution does all the computations first, then goes back to the beginning to generate the plots, which for some reason it can't do correctly in Section 1. I've seen this in live scripts and and m-scripts. Is this expected behavior? If so, it's a bit disconcerting that outputs from commands in Section 1 are influenced by executon of commands in Section 2.
FWIW, I was using "clear all" in Section 2 to make sure that I cleared out all of the symbolic math assumptions from Section 1. But I think I've now found a better (correct?) way to do that, so this issue isn't holding me up at present.
% Section 1
clear all %#ok
syms t real
s(t) = piecewise(t<-1,0, t>2,0, exp(-abs(t)));
figure;
fplot(s(t),[-3 3],'MeshDensity',50)
% Section 2
clear all %#ok
syms t real
s(t) = exp(-abs(t))*rectangularPulse(-2,2,t);
figure;
fplot(s(t),[-15 15],'MeshDensity',50)
3 Comments
Sargondjani
on 14 Nov 2021
Did you read the documentation on "clear all"? I mean, I agree it is weird, but best way is probably to avoid clear all, as recommended in the documentation.
Paul
on 14 Nov 2021
Rik
on 15 Nov 2021
I think I would classify this at least as unexpected behavior, if not outright as a bug. Did you contact support already?
The mere fact there are better alternatives (as I expected) doesn't change that.
Accepted Answer
More Answers (1)
Sulaymon Eshkabilov
on 15 Nov 2021
0 votes
In such cases, it is best to use: clearvars instead of clear all
Categories
Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
