placing values in the form of a triangle in a matrix

4 Ansichten (letzte 30 Tage)
Duncan
Duncan am 11 Aug. 2014
Kommentiert: Duncan am 11 Aug. 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?

Akzeptierte Antwort

Hikaru
Hikaru am 11 Aug. 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

Weitere Antworten (1)

Patrik Ek
Patrik Ek am 11 Aug. 2014
Bearbeitet: Patrik Ek am 11 Aug. 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.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by