How can I make this nested for loop work?

1 view (last 30 days)
Deepanwita
Deepanwita on 13 May 2013
I want to store values in 'temp1' and 'temp2' dynamically. I have predefined them so no problem with the speed. This is my code for getting the value of 'bc' using for loop of 'obj'. This is inside the for loop run by 'i'. In the very first run of outer for loop i.e. i=1, I need to have the inner for loop run first completely and then the values of bc(1) be stored in temp1(1) and bc(2) in temp2(2). And then value of 'i' should increment by 1 and next time the values of bc(1) and bc(2) be stored in temp1(2) and temp2(2) respectively and so on.
for i=1:10
for obj = 1:length(stats)
bc = stats(obj).Centroid;
end
temp1(i)=bc(1);
temp2(i)=bc(2);
end
What's happening now is that the last value of bc(1) and bc(2) are getting stored in temp1 and temp2 all through i=1:10. Please correct me.

Answers (2)

Matthew Doveton
Matthew Doveton on 13 May 2013
Is what you are trying to achieve to save every bc(1) and bc(2) values into temp1 and temp2? if so I think this is what you are trying to do:
temp1 = zeros(1,length(stats)); %create vector of correct length
temp2 = zeros(1,length(stats));%create vector of correct length
%loop through all bc values and save in temps
for obj = 1:length(stats)
bc = stats(obj).Centroid;
temp1(obj)=bc(1);
temp2(obj)=bc(2);
end
This would collect all the bc(1) and bc(2) values into temp1 & temp2. If you are just after a certain amount then
N = 10; %amount after
temp1 = zeros(1,N); %create vector of correct length
temp2 = zeros(1,N);%create vector of correct length
%loop through selected number
for obj = 1:N
bc = stats(obj).Centroid;
temp1(obj)=bc(1);
temp2(obj)=bc(2);
end
If this is not what you are after could you elaborate.
  1 Comment
Matthew Doveton
Matthew Doveton on 13 May 2013
In your example you are looping through all Stats on every iteration, bc only ever holds the last Stats value (Stats(length(Stats)).Centroid). You are then saving this value throughout both Temp arrays.

Sign in to comment.


James Kristoff
James Kristoff on 13 May 2013
There is currently nothing in the code you provided to change the value of bc from one loop to the next. The code you have written is equivalent to:
for obj = 1:length(stats)
bc = stats(obj).Centroid;
end
for i=1:10
temp1(i)=bc(1);
temp2(i)=bc(2);
end
As you are not utilizing the looping variable i in the Centroid Loop.
It is not clear why the Centroid loop needs to complete before moving on, as this loop keeps overwriting the value bc, which is why the last value is always written to the temp1/temp2 vectors. Perhaps what you wanted to do was:
for i = 1:length(stats)
bc = stats(i).Centroid;
temp1(i)=bc(1);
temp2(i)=bc(2);
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!