How to create triangle inside matrix?

What if I wanted a triangle of numbers from the formula (2n-1) that resulted in a triangle inside a matrix such that...
[0 0 0 0 1 0 0 0 0]
0 0 0 2 1 2 0 0 0
0 0 3 2 1 2 3 0 0
0 4 3 2 1 2 3 4 0]
etc?...

 採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 8 月 30 日

3 投票

sort(spdiags(toeplitz(1:n)))

4 件のコメント

Billy Albritton
Billy Albritton 2016 年 8 月 30 日
Stop being a genius. :-)
Billy Albritton
Billy Albritton 2016 年 8 月 30 日
What if I want to write a loop script to do the same thing?
Andrei Bobrov
Andrei Bobrov 2016 年 8 月 30 日
編集済み: Andrei Bobrov 2016 年 8 月 30 日
Hi Billy!
With loop:
a = zeros(n,2*n-1);
for jj = 1:n
a(jj,n-jj+1:n+jj-1) = [jj:-1:1,2:jj];
end
Billy Albritton
Billy Albritton 2016 年 9 月 10 日
Thank you! You are amazing!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by