How to simplify matrix expression

2 ビュー (過去 30 日間)
cniv_we
cniv_we 2016 年 6 月 21 日
コメント済み: cniv_we 2016 年 6 月 21 日
I have following matrix expression:
y_ = zeros(5000,10);
y_(1:500,10) = 1;
y_(501:1000,1) = 1;
y_(1001:1500,2) = 1;
y_(1501:2000,3) = 1;
y_(2001:2500,4) = 1;
y_(2501:3000,5) = 1;
y_(3001:3500,6) = 1;
y_(3501:4000,7) = 1;
y_(4001:4500,8) = 1;
y_(4501:5000,9) = 1;
y = y_;
How do I simplify this code under 2 or 3 lines? At the end I just want to have a matrix Y containing 5000x10 elements.
  2 件のコメント
John D'Errico
John D'Errico 2016 年 6 月 21 日
Learn to use sparse.
cniv_we
cniv_we 2016 年 6 月 21 日
I think loop is enough. I tried this:
y = zeros(5000,10);
y(1:500,10) = 1;
j = 500;
for i=1:9
j = 500;
y(i*j+1:(i+1)*j,i) = 1;
y
end
Any more elegent way?

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

回答 (1 件)

John D'Errico
John D'Errico 2016 年 6 月 21 日
編集済み: John D'Errico 2016 年 6 月 21 日
Will one line suffice?
y = sparse((1:5000)',reshape(repmat([10,1:9]',1,500)',[5000,1]),1,5000,10);
  1 件のコメント
cniv_we
cniv_we 2016 年 6 月 21 日
That's great! Thanks.

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by