problem with operations with a for loop

조회 수: 1 (최근 30일)
Natalia
Natalia 2013년 4월 18일
편집: Walter Roberson 2024년 8월 19일
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
per isakson
per isakson 2013년 4월 18일
편집: per isakson 2013년 4월 18일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Abhinaya Kennedy
Abhinaya Kennedy 2024년 8월 19일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by