How to reset variables before each iteration
87 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2016-5-25
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.
回答(3 个)
Charles Robinson
2022-2-18
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 个评论
Jos (10584)
2016-5-25
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 个评论
Are Mjaavatten
2016-5-25
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 个评论
Are Mjaavatten
2016-5-25
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Database Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!