Indexing inside a for loop when satisfying a condition

4 vues (au cours des 30 derniers jours)
Sreekanth Nandakumar
Sreekanth Nandakumar le 16 Avr 2019
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))=[];

Réponse acceptée

Bob Thompson
Bob Thompson le 16 Avr 2019
Modifié(e) : Bob Thompson le 16 Avr 2019
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.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by