How to create triangle inside matrix?

What if I wanted a triangle of numbers from the formula (2n-1) that resulted in a triangle inside a matrix such that...
[0 0 0 0 1 0 0 0 0]
0 0 0 2 1 2 0 0 0
0 0 3 2 1 2 3 0 0
0 4 3 2 1 2 3 4 0]
etc?...

 Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 30 de Ag. de 2016
sort(spdiags(toeplitz(1:n)))

4 comentarios

Billy Albritton
Billy Albritton el 30 de Ag. de 2016
Stop being a genius. :-)
Billy Albritton
Billy Albritton el 30 de Ag. de 2016
What if I want to write a loop script to do the same thing?
Andrei Bobrov
Andrei Bobrov el 30 de Ag. de 2016
Editada: Andrei Bobrov el 30 de Ag. de 2016
Hi Billy!
With loop:
a = zeros(n,2*n-1);
for jj = 1:n
a(jj,n-jj+1:n+jj-1) = [jj:-1:1,2:jj];
end
Billy Albritton
Billy Albritton el 10 de Sept. de 2016
Thank you! You are amazing!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 30 de Ag. de 2016

Comentada:

el 10 de Sept. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by