How to reset variables before each iteration
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi,
I have many variables, and I want to reset all variables except two variables before each iteration. Can anyone kindly tell how to do this.
Many thanks in advance
1 Kommentar
Stephen23
am 25 Mai 2016
clear-ing variables slows your code down. The best plan would be to simply reallocate to those variables in each loop, so clearing is no required.
Antworten (3)
Charles Robinson
am 18 Feb. 2022
I assume it is inefficient to clear variables, so better to simply overwrite as noted above: e.g.
A = A0; or
A = zeros(sizeofA)
If you are "building" the data (i.e. changing the variable size with each iteration, not recommended), or if sparsely initializing a matrix, you need to remove any values that may be lingering, e.g.:
A = []; A(idx) = A0;
I don't know if "emptying" is better than clearing A. Try both and let us know!
0 Kommentare
Jos (10584)
am 25 Mai 2016
I think I miss the point, but this will do what you are asking for:
A0 = 7 ;
B = 1 ;
for k=1:10 % iteration
A = A0 % reset one variable
B = k*A + 2*B + k % calculations that change another variable
end
0 Kommentare
Are Mjaavatten
am 25 Mai 2016
Here is an example that clears all variables except b and c:
% Fist create some variables
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
%
% The cell array keepvars should contain the names of all variables
% that you want to keep, plus the variables that you need in the process:
keepvars = {'b','c','keepvars','ix','varlist'};
varlist = whos;
for ix = 1:length(varlist)
if ~strcmp(varlist(ix).name,keepvars)
clear(varlist(ix).name);
end
end
% Finally, clear the intermediate variables:
clear ix varlist keepvars
1 Kommentar
Are Mjaavatten
am 25 Mai 2016
I should add that although this may (or may not?) answer your question, it is not an example of good programming practice. It would be better to write your iteration code in such a way that there is no need to clear or reset variables.
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!