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';
  1 件のコメント
Julia  Curtis
Julia Curtis 2020 年 3 月 22 日
Thank you! It works beautifully !!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by