Indexing inside a for loop when satisfying a condition
3 ビュー (過去 30 日間)
古いコメントを表示
Sreekanth Nandakumar
2019 年 4 月 16 日
コメント済み: Sreekanth Nandakumar
2019 年 4 月 16 日
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!