# The most efficient way to locate the first 1's in each row of a matrix

20 visualizaciones (últimos 30 días)
Ulrik William Nash el 19 de Oct. de 2019
Comentada: Jos (10584) el 21 de Oct. de 2019
I have a potentially large r by c matrix, m, consisting of 1's and 0's. What is the most efficient way create a r by 1 vector, v, containing the index of the first 1 in each row of m.
For example,
m = [0 1 1;1 0 0; 0 0 1]
should result in
v = [2;1;3]
##### 0 comentariosMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos

Iniciar sesión para comentar.

### Respuestas (2)

Star Strider el 19 de Oct. de 2019
The max function will return the indices of the first instances of the maximum value it encounters, in the desired dimension. Since your matrix only has (0,1), it is appropriate here.
This:
m = [0 1 1;1 0 0; 0 0 1];
[~,v] = max(m,[],2)
produces:
v =
2
1
3
##### 1 comentarioMostrar NingunoOcultar Ninguno
Jos (10584) el 21 de Oct. de 2019
nice! One can shorten it to:
[~, v] = max(m')
... but what if there is no 1 in a row

Iniciar sesión para comentar.

Jos (10584) el 19 de Oct. de 2019
m = [0 1 1 1 ;1 0 1 0; 0 0 1 1 ; 0 0 0 1]
% a simple solution
[r, c] = find(m') ;
clear v1
v1(r,1) = c
% another solution
[v2, ~] = find(cumsum(cumsum(m,2),2)==1)
##### 0 comentariosMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos

Iniciar sesión para comentar.

### Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by