How to reset variables before each iteration

조회 수: 82 (최근 30일)
Mekala balaji
Mekala balaji 2016년 5월 25일
답변: Charles Robinson 2022년 2월 18일
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
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
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!

Jos (10584)
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

Are Mjaavatten
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
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 CenterFile Exchange에서 Database Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by