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

조회 수: 2 (최근 30일)
Julia  Curtis
Julia Curtis 2020년 3월 19일
댓글: Julia Curtis 2020년 3월 22일
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

채택된 답변

James Tursa
James Tursa 2020년 3월 19일
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';

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by