MATLAB Answers

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

1 view (last 30 days)
Julia  Curtis
Julia Curtis on 19 Mar 2020
Commented: Julia Curtis on 22 Mar 2020
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

  0 Comments

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 19 Mar 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';

  1 Comment

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Products


Release

R2019a