How to replace zero with one automatically in MATLAB

4 ビュー (過去 30 日間)
Stephen john
Stephen john 2022 年 3 月 18 日
編集済み: Stephen23 2022 年 3 月 18 日
Hello everyone , i hope you are doing well.
i have the following code in which i create array of 6000x6 manualy and replace zero with one for every 1000 rows
like first column has ones in 1 to 1000, then second column has ones from 1001 to 2000.
I want it to be done by automatically or single line
Can anybody help me
labels=zeros(6000,6);
labels(1:1000,1)=1;
labels(1001:2000,2)=1;
labels(2001:3000,3)=1;
labels(3001:4000,4)=1;
labels(4001:5000,5)=1;
labels(5001:6000,6)=1;

回答 (1 件)

Stephen23
Stephen23 2022 年 3 月 18 日
編集済み: Stephen23 2022 年 3 月 18 日
Here are three approaches:
M1 = repelem(eye(6,6),1000,1)
M1 = 6000×6
1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0
M2 = kron(eye(6,6),ones(1000,1))
M2 = 6000×6
1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0
C = repmat({ones(1000,1)},1,6);
M3 = blkdiag(C{:})
M3 = 6000×6
1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0
isequal(M1,M2,M3) % checking
ans = logical
1

カテゴリ

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

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by