How to reset variables before each iteration
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 25 de Mayo de 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.
Respuestas (3)
Charles Robinson
el 18 de Feb. de 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 comentarios
Jos (10584)
el 25 de Mayo de 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 comentarios
Are Mjaavatten
el 25 de Mayo de 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 comentario
Are Mjaavatten
el 25 de Mayo de 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.
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!