フィルターのクリア

placing values in the form of a triangle in a matrix

3 ビュー (過去 30 日間)
Duncan
Duncan 2014 年 8 月 11 日
コメント済み: Duncan 2014 年 8 月 11 日
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?

採用された回答

Hikaru
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
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.
  1 件のコメント
Duncan
Duncan 2014 年 8 月 11 日
thanks. it works

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by