placing values in the form of a triangle in a matrix
5 ビュー (過去 30 日間)
古いコメントを表示
I want to write a code which does the following:
say my input is '5' , the code will run and the output will be in a matrix in the form
1 6 10 13 15
2 7 11 14
3 8 12
4 9
5
or if my input is '3'
1 4 6
2 5
3
any ideas on how I should start?
0 件のコメント
採用された回答
Hikaru
2014 年 8 月 11 日
If you want it to be a matrix, then I don't think there is a way to do it without adding 0's in the lower part of the triangle. The code below will work.
n = 3; %input
A = hankel(1:n);
c = A(n,1);
for i = 2:n
for j = 1:n-1
A(j,i) = c+1;
c = c + 1;
end
n = n-1;
end
その他の回答 (1 件)
Patrik Ek
2014 年 8 月 11 日
編集済み: Patrik Ek
2014 年 8 月 11 日
Try this,
n = 5;
A0 = fliplr( triu(ones(n)) );
A = cumsum( A0(:) );
A = reshape(A,n,n);
A(A0<=0) = 0
The idea is to create an upper diagonal matrix of ones which you flip, then accumulate the sum of all elements (after reshaping the elements to a column matrix with (:) ). That means that the sum increase for every element, represented in the final matrix, but not for any other element. Then reshape the matrix again and set all elements which are not the flipped upper diagonal to zero to zeros.
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!