How to reset variables before each iteration
82 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Stephen23
le 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.
Réponses (3)
Charles Robinson
le 18 Fév 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 commentaires
Jos (10584)
le 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 commentaires
Are Mjaavatten
le 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 commentaire
Are Mjaavatten
le 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.
Voir également
Catégories
En savoir plus sur Database Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!