placing values in the form of a triangle in a matrix

9 visualizaciones (últimos 30 días)
Duncan
Duncan el 11 de Ag. de 2014
Comentada: Duncan el 11 de Ag. de 2014
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?

Respuesta aceptada

Hikaru
Hikaru el 11 de Ag. de 2014
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

Más respuestas (1)

Patrik Ek
Patrik Ek el 11 de Ag. de 2014
Editada: Patrik Ek el 11 de Ag. de 2014
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.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by