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

2 次查看(过去 30 天)
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