problem with operations with a for loop

1 vue (au cours des 30 derniers jours)
Natalia
Natalia le 18 Avr 2013
Modifié(e) : Walter Roberson le 19 Août 2024
I'm performing a number of operations inside of a for loop. All the operations are being performed with the exception of the last loop.
e.g if I have within a loop something like this
for t=1:4
.....some code....
unmated=find(fem(:,3,t)==0)
fem(:,8,t)=fem(:,1,t); %replacing fem(unmated,8,t)=0;
....more code... end
the operations are only performed for the first 3 loops but not for the last one.
Any ideas?
Thanks
  1 commentaire
per isakson
per isakson le 18 Avr 2013
Modifié(e) : per isakson le 18 Avr 2013
It is difficult to read the code because of poor formatting. However, I cannot spot the reason why the loop is not executed for t=4. I guess, the reason is to find outside the code you show.

Connectez-vous pour commenter.

Réponses (1)

Abhinaya Kennedy
Abhinaya Kennedy le 19 Août 2024
Since you have not provided the entire code, here is a generic set of steps you can do to figure out what the problem might be.
  1. Ensure that fem has enough elements in the third dimension to accommodate the loop. If fem is smaller than expected, the loop might not execute as intended for the last iteration.
  2. Make sure the condition fem(:,3,t)==0 is being met for the last iteration. If no elements satisfy this condition, unmated will be empty, and the subsequent operations won’t be performed.
  3. Ensure that no other part of your code is overwriting the values in fem during the loop, especially in the last iteration.
  4. Sometimes, issues arise due to boundary conditions. Double-check any operations that might behave differently at the edges of your data.
  5. Add some debugging statements to check the values of t, unmated, and fem during each iteration. This can help identify where the issue occurs.
for t = 1:4
disp(['Iteration: ', num2str(t)]);
% Your code here
unmated = find(fem(:,3,t) == 0);
disp(['Unmated indices: ', num2str(unmated')]);
fem(:,8,t) = fem(:,1,t); % Replacing fem(unmated,8,t) = 0;
disp(['fem(:,8,t): ', num2str(fem(:,8,t)')]);
% More code here
end
Run this modified loop and observe the output to gain insights into what might be happening during the last iteration. Adjust the logic as necessary based on your findings.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by