Using the find function in a loop
조회 수: 1 (최근 30일)
이전 댓글 표시
Can the find function be used in a loop? I have not been able to get it to work. I have tried many ways but the find command doesn't seem to like "i" in the statement. Here are two different ways I have tried it:
%Inititalize variables (P1 is a vector generated earlier in the program)
P1_int(1)=1;
i=1;
c=(1:length(P1)-1);
intdurl(1)=intdur;
for i=2:21 P1_int(i)=find((ttot(c)<intdurl(i-1)) & (ttot(c+1)>intdurl(i-1))); % determines i when ttot is intdurl(i-1)
intdurl(i)=intdurl(i)+intdur;
end
I have also tried:
%Inititalize variables (P1 is a vector generated earlier in the program)
P1_int(1)=1;
i=1;
c=(1:length(P1)-1);
intdur=5;
for i=2:21 P1_int(i)=find((ttot(c)<intdur*(i-1) & (ttot(c+1)>intdur*(i-1))); % determines i when ttot is intdur*(i-1)
end
Thanks!
댓글 수: 0
채택된 답변
the cyclist
2011년 4월 13일
Your code fails when i=21, because the second condition [(ttot1min(c+1)>intdur*(i-1))] is never met, resulting in the find command giving an empty array.
I discovered this by first outputing the value of i, to see what iteration it crashed on, then using a conditional breakpoint at i==21, and poking into the pieces of the right-hand side.
댓글 수: 0
추가 답변 (2개)
Matt Fig
2011년 4월 13일
Is it possible that your find command is returning multiple results? If so, putting multiple results into a single element of an array will not work. Of course it would help if you showed the error message...
댓글 수: 0
the cyclist
2011년 4월 13일
The find command can certainly be used in a loop. Here are a few suggestions:
- Your code is not executable as written. It would be really handy if you could fill in values for the undefined variables, such that the code will run and exhibit the problem.
- Tell us the error or warning you are getting.
- The find command might be giving a single scalar value, or a vector, or an empty array as output. Can your code handle all that, as needed?
- Try breakpointing your code at the line where the find command is called, and see if anything suspicious is happening, or if you can manually run some sections of that line to see if it gives what you suspect.
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!