Info

This question is closed. Reopen it to edit or answer.

Variable in nested loop remebers its value at last value of the same iteration from previous parent iteration-- scope issue I guess

1 view (last 30 days)
please relate to the code at the end of the question
R is a horizontal vector or 1*6 matrix
S is 6*6 matrix
I am trying to create rows for sorted_S one in each iteration of parent loop by initialising a vector f_temp whose elements are appended to it through the inner loop and subsequently . What I expect is that every iteration of the parent loop initialises f_temp to an empty matrix which should be initialised as 1*6 matrix by the inner loop but what is actually happening is the parent loops initialised f_temp to an empty matrix in each iteration but the inner loop along not only creates elements for the current iteration but it also creates the same index element for the previous parent iteration. for example if after first parent iteration
f_temp= [1 2 3 4 5]
and then following the statements
f_temp =[]
after entering into the child loop
it creates f_temp as following in each child iteration
f_temp=[1;7]
f_temp=[1 2;7 8]
f_temp = [1 2 3;7 8 9]
and the pattern follows.
while I only want to get f_temp = [7 8 9 ... n]
how to resolve the issue
sorted_S = [];
for i=1:rows
f_temp=[];%declared and initialised for the first time
for j=1:rows_O
if ismember(j,R)
f_temp = [f_temp,S(R(1:i),j)];
end
end
sorted_S=[sorted_S;sort(f_temp)];
end

Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!