Indexing inside a for loop when satisfying a condition
4 次查看(过去 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 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!