How do I fill a matrix of 1s and 0s with sequential numbers

2 visualizaciones (últimos 30 días)
I have a matrix A = [0 0; 1 0; 1 1; 1 1] and a matrix B = [1 1; 0 1; 0 0; 0 0].
Instead of 1s, I want to fill matrix A with sequential numbers from 1 to --- wherever there is a 1 located. It should look lile this: A = [0 0; 1 0; 2 3; 4 5].
The same goes for matrix B but the first number should be sequential to the last number on matrix A. It should look like this: B = [6 7; 0 8; 0 0; 0 0].
Zeros need to remain zeros.
Thank

Respuesta aceptada

James Tursa
James Tursa el 19 de Mzo. de 2020
nnza = nnz(A);
nnzb = nnz(B);
At = A';
Bt = B';
At(logical(At)) = 1:nnza;
Bt(logical(Bt)) = (nnza+1):(nnza+nnzb);
Aresult = At';
Bresult = Bt';

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by