# Toeplitz Matrix (diagonal-constant matrix)

Hello all,

I want to create a Toeplitz matrix which I need to invert. Do anyone know a good way to create one? The way I have take way too many steps.

``````Int_t n = 3; // n x n matrix
Double_t a[] = {1,2,3};
TVectorD aa;
aa.Use(n,a);

TMatrixD A(n,n);
TMatrixDRow(A,0) = aa;

//here is a for to reallocate the elements and fill the matrix
for(Int_t i = 1; i<n; i++){ // this for to fill the matrix
Double_t temp = aa[0];
aa[0] = aa[n-1];
for(Int_t j = 1; j<n;j++){
Double_t temp2 = aa[j];
aa[j] = temp;
temp = temp2;
}
TMatrixDRow(A,i) = aa;
}
for(Int_t i = 0; i<n; i++){
for(Int_t j = 0; j<n; j++){
cout << A[i][j] << " ";
}
cout << "\n";
}
``````

OBS.: The application is for Wiener Filter

Cheers,
Henrique

ROOT Version: 6.26/02
Platform: Ubuntu 21.10 impish (x86-64)
Compiler: (gcc/g++ 11.2.0)

I guess you should just follow the definition of such matrix.

Sorry, I didn’t follow you. I am using the definition of the matrix there. It is just that root does not accept negative values, so I though it would be easy this way.

Ak ok… sorry. @moneta oneta may have an idea in that case.

Hi Henrique,

Not sure what you expect because what you wrote is already quite compact.
The swapping could be done in one line :

``````void toeplitz()
{
Int_t n = 3; // n x n matrix
Double_t a[] = {1,-2,3};
TVectorD aa;
aa.Use(n,a);

TMatrixD A(n,n);
TMatrixDRow(A,0) = aa;

//here is a for to reallocate the elements and fill the matrix
for(Int_t i = 1; i<n; i++){ // this for to fill the matrix
Double_t temp = aa[0];
aa[0] = aa[n-1];
for(Int_t j = 1; j<n;j++)
std::swap(aa[j],temp);
TMatrixDRow(A,i) = aa;
}

A.Print();
}
``````

or are you looking for something more “elegant” ? It could be done with TMatrixDDiag and TMatrixDSub but it will not be shorter .

-Eddy

Thanks a lot for the reply. I liked the `std::swap` method there.
I was wondering if there was any function member of TMatrixD that could do it
I’ve stepped into a solution for M x M matrices:

``````Int_t M = 3; // M x M matrix
Double_t a[] = {1,-2,3};
TMatrixD A(M,M);

for (int i=0; i<M; i++)
{
for (int j=0; j<M; j++)
{
A[i][j] = aa[abs(i-j)];
}
}
``````

Thanks again.

Cheers,
Henrique

Just for the record, your code examples do create Toeplitz matrices but very specific ones, where the last one is symmetric and the first one permutates the off-diagonal values.

Any Toeplitz can be written by the following code (Notice the upper and lower boundary of the TVectorD:

`````` Int_t M = 3; // M x M matrix
TMatrixD A(M,M);
Double_t a[] = {1,2,3,4,5};

TVectorD aa(-M+1,M-1);
aa.Use(-M+1,M-1,a);

for (int i=0; i<M; i++)
{
for (int j=0; j<M; j++)
{
A[i][j] = aa[j-i];
}
}
``````