Question

Is there an efficient way to produce square multi-diagonal matricies such as these:

[[1,2,3],
 [2,1,2],
 [3,2,1]]

[[1,2,3,4,5],
 [2,1,2,3,4],
 [3,2,1,2,3],
 [4,3,2,1,2],
 [5,4,3,2,1]]

My efforts so far have produced the following:

t=10
sum=zeros(t,t)
for i=1:t
 sum+=diag(ones(1,i)*(t-i)+1,t-i);
end
sum
sum+sum'-diag(ones(1,10),0)
Était-ce utile?

La solution

The command toeplitz does exactly what you want:

toeplitz([1,2,3,4,5,6])

ans =

 1     2     3     4     5     6
 2     1     2     3     4     5
 3     2     1     2     3     4
 4     3     2     1     2     3
 5     4     3     2     1     2
 6     5     4     3     2     1

Autres conseils

What you are looking for is called a symmetric (Hermitian) toeplitz matrix.

I'm not familiar with matlab, but I found this documentation on mathworks:

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top