Search code examples
c++for-loopeigenallocationdiagonal

5 Diagonal Matrix and for loops


Is there an easier way to construct a 5 Diagonal matrix in Eigen? I can probably run for loops and allocate diagonals and zeros, but I did come across Diagonal<> just not sure how to use it for 5 diagonals, instead of one. Any ideas? EDIT: Figured this one out! For those wondering; you can use

matrix.diagonal(+n) = vector;
matrix.diagonal(-n) = vector;

to access super/sub diagonals of a matrix and write over them with vectors.

General side question: Is there a way I can skip an allocation when running a for loop in C++? For example:

int n; //size of matrix
MatrixXd m(n,n); //nxn matrix

for(int i=0; i<n; i++)
{ 
   m(i,i) = 5; 
   m(i,i+1) = 6;
   m(i,i-1) = 4;
   m(i,i+2) = 7;
   m(i,i-2) = 3;
}


for (int i=0; i<n; i++)
{
    for(int j=0; j<n; j++)
    {
         if(m(i,j) = something) //I want the loop to skip m(i,j) where 
            break;              //i have already allocated values to m(i,j)
                                //How do I do that, in general, in C++?      
         else
       { m(i,j) = 0;}
    }
 }

Thanks


Solution

  • It sounds like you want to skip the diagonals because they've already been initialized (allocated is not the correct term here).
    Looking at your loop where you set the diagonals you can see that each (i,j) that you set obeys abs(i-j) <= 2. For example, when you set the element (i, i+2) -> abs(i-(i+2)) -> abs(-2) -> 2 which is less than or equal to 2.

    So the condition in your second loop should be:

    if (abs(i-j) <= 2)
      continue;//break will exit the loop, continue will skip to the next iteration