Finding column index of the first instance of 1

I have a logical array like this:
I want to extrat the colum index of the cells where the first instance of 1 is detected. Like this:
For example, you see here that the first two rows show 4, because that is where 1 is first detected.

 Respuesta aceptada

C = sum(cumprod(~X, 2),1) + 1;
C will be one more than the number of columns for any row that has no 1.

4 comentarios

Pelajar UM
Pelajar UM el 2 de Mayo de 2022
Editada: Pelajar UM el 2 de Mayo de 2022
This works, with a little adjustment:
C = sum(cumprod(~X, 2),2) + 1;
Now imagine X was computed inside a for loop. In the example above, k=1:5000
Is there a way to stop the loop before 5000 when all the rows have at least a 1?
Basically, I have a difficult time bringing C inside the loop and getting reasonable results....
idx = find(sum(A,2)==0)
if idx == []
break
end
But I don't know if it's more time-consuming to check the above condition for each k or to make MATLAB build the matrix A completely and to check the condition after the loop has finished.
Pelajar UM
Pelajar UM el 3 de Mayo de 2022
Editada: Pelajar UM el 3 de Mayo de 2022
Thanks @Torsten. The second line gives a warning:
Unexpected use of '[' in a scalar context.
And it appears to break the loop already in k=1.
Instead we can use
if isempty(idx) == 1
break
end
But checking idx in every loop takes longer.
Method 1: 22 seconds
Method 2: 528 seconds
isempty(idx)

Iniciar sesión para comentar.

Más respuestas (1)

Jonas
Jonas el 2 de Mayo de 2022

0 votos

use the find() function together with a loop over each row

1 comentario

Pelajar UM
Pelajar UM el 2 de Mayo de 2022
Editada: Pelajar UM el 2 de Mayo de 2022
Like this?
Doesn't work, because it doesn't find the first instance. It finds all the indices that meet this condition.
for p=1:n %n is the length of the logical array X
G(p,:)=find (X(p,:));
end

Iniciar sesión para comentar.

Categorías

Etiquetas

Preguntada:

el 2 de Mayo de 2022

Comentada:

el 3 de Mayo de 2022

Community Treasure Hunt

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

Start Hunting!

Translated by