Filter löschen
Filter löschen

Indexing inside a for loop when satisfying a condition

3 Ansichten (letzte 30 Tage)
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))=[];

Akzeptierte Antwort

Bob Thompson
Bob Thompson am 16 Apr. 2019
Bearbeitet: Bob Thompson am 16 Apr. 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.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by