2.2.3.9.28 matrixbase::GetDiagonal

Description

Get the diagonal or N-th diagonal of this matrix.

Syntax

int GetDiagonal( vectorbase & vbDiagonal, int nNthDiagonal = 0 )

Parameters

vbDiagonal
[output] The result vector containing the (N-th) diagonal
nNthDiagonal
[input] The number specifying the N-th diagonal, default 0 is the main diagonal, > 0 is above the main diagonal, and < 0 is below the main diagonal.

Return

Returns 0 on success and a non-zero error code on failure.

Examples

EX1

void matrixbase_GetDiagonal_ex1()
{
int ii,jj;
matrix<double> mat1 = {
{ 0,  1, 99,  1,  1},
{ 1, 99,  1,  1,  1},
{99,  1,  0,  1,  1}
};
for(ii=0; ii<3; ii++)
for(jj=0; jj<5; jj++)
if(mat1[ii][jj]==99)
mat1[ii][jj]=NANUM;
vector vR;
int rc = mat1.GetDiagonal(vR);
if(rc!=0)
printf("Error: GetDiagonal failed. rc=%d\n", rc);
else{
for(int ii = 0; ii < vR.GetSize(); ii++)
printf("\t%g",vR[ii]);
}
}

EX2

// Get the diagonal of a matrix, and put it into a vector
void matrixbase_GetDiagonal_ex2()
{
int ii,jj;
matrix<double> mat1 = {
{ 0,  1, 99,  1,  1},
{ 1, 99,  1,  1,  1},
{99,  1,  0,  1,  1}
};
for(ii=0; ii<3; ii++)
for(jj=0; jj<5; jj++)
if(mat1[ii][jj]==99)
mat1[ii][jj]=NANUM;  // set row=ii,col=jj to NANUM
//  Input matrix is:
//        { 0,  1, --,  1,  1}
//        { 1, --,  1,  1,  1}
//        {--,  1,  0,  1,  1}

//   Output diagonal vector is:
//        { 0, --,  0}

MatrixPage MatPg1;
MatPg1.Create("Origin");
MatrixLayer MatLy1 = MatPg1.Layers(0);
Matrix Mat1(MatLy1);
Mat1 = mat1;
printf("  Input matrix is %s.\n",Mat1.GetName());

MatrixPage MatPg2;
MatPg2.Create("Origin");
MatrixLayer MatLy2 = MatPg2.Layers(0);
Matrix Mat2(MatLy2);

vector vec1;

int rc=Mat1.GetDiagonal(vec1); //Put the upper triangular matrix of Mat1 to Mat2
if(rc!=0)
printf("  Error: GetDiagonal failed. Error Code=%d\n",rc);
else
{
Mat2.SetSize(1,vec1.GetSize());
Mat2.SetRow(vec1, 0);  // Set 2nd Row(as the index starts 0) of Mat2
printf("  Vector from the diagonal is placed in %s.\n",Mat2.GetName());
printf("  Note that the NANUM value in the diagonal is preserved,\n");
}

MatrixPage MatPg3;
MatPg3.Create("Origin");
MatrixLayer MatLy3 = MatPg3.Layers(0);
Matrix Mat3(MatLy3);

vector vec2;

rc=Mat1.GetDiagonal(vec2,-1); //Get the 1th diagonal below the main diagonal
if(rc!=0)
printf("  Error: GetDiagonal failed. Error Code=%d\n",rc);
else
{
Mat3.SetSize(1,vec2.GetSize());
Mat3.SetRow(vec2, 0);
printf("  Vector from the diagonal is placed in %s.\n",Mat3.GetName());
printf("  Note that the NANUM value in the diagonal is preserved,\n");
}
}

Remark

Get the diagonal or N-th diagonal of this matrix and place the result in a vector. The result vector and this matrix must have the same underlying base type or a run time error will be generated.