placing values in the form of a triangle in a matrix

조회 수: 9 (최근 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.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by