Indexing inside a for loop when satisfying a condition
조회 수: 3 (최근 30일)
이전 댓글 표시
Hello all,
I have a question regarding indexing. Please check the code below. I want to return the index values into the vector 'Index' from the vector 'indices_res' when the if condition satisfy. The first instance of my index is when j=23. I get the Vector 'Index' but the value goes to the 23rd row and the remaining 22 rows are Zeros. I understand that it is due to my definition as Index(j-1,:), but Is there any way for me to avoid zeros and just add the values for each loop when the condition satisfy ? Now my vector Index is a 256x1 matrix, but I should get it as a 19x1 matrix after avoiding every zeros.
for j=2:N
indices_res(j-1,:)=find(abs(AT-Pos(j))<10^-3);
if(Pulse(j-1)==10)
Index(j-1,:)=indices_res(j-1);
I can remove the zeros later with the below code line but I want to avoid that extra code line.
Index(all(Index==0,2))=[];
댓글 수: 0
채택된 답변
Bob Thompson
2019년 4월 16일
편집: Bob Thompson
2019년 4월 16일
I usually get around this by having a second index which is advanced only with the condition.
c = 1; % Index of 'Index'
for j=2:N
indices_res(j-1,:)=find(abs(AT-Pos(j))<10^-3);
if(Pulse(j-1)==10)
Index(c,:)=indices_res(j-1);
c = c+1; % Advance for next value
If you're really worried about extra lines of code then this is probably not your best option, as I added not only one, but two lines of code. Personally, I am not as worried about the number of lines as much as how efficient it is, and I generally feel that it is more efficient to have a counting variable than to create and remove a number of elements from an array. Totally a matter of mental efficiency, I have no idea if it is more efficient for the computer or not.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!