2.2.3.9.62 matrixbase::SetDiagonal

Description

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

Syntax

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

Parameters

vbDiagonal
[input] The source 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 or a non-zero error code on failure.

Examples

EX1

// Set a vector to the diagonal of a matrix
void matrixbase_SetDiagonal_ex1()
{
int rc, ii,jj;

matrix<double> mat1 = {
{ 2,  1, 99,  1,  1},
{ 1, 99,  1,  1,  1},
{99,  1,  2,  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:
//        { 2,  1, --,  1,  1}
//        { 1, --,  1,  1,  1}
//        {--,  1,  2,  1,  1}

vector vec1 = {1, 1, 1};  //Vector for the diagonal of the output matrix

//   Output matrix with all 1s at the diagonal:
//        {1,  0,  0}
//        {0,  1,  0}
//        {0,  0,  1}

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);
Mat2=mat1;

rc=Mat2.SetDiagonal(vec1); //Put 1s into the diagonal of Mat2
if(rc!=0)
printf("  Error: SetDiagonal failed. Error Code=%d\n",rc);
else {
printf("  Output matrix with 1s at the diagonal is %s.\n",Mat2.GetName());
printf("  Note that the output matrix is a square matrix.\n");
printf("  Note that all cells in the non-diagonal area became 0s.\n");
}
}

Remark

Set the diagonal or N-th diagonal of this matrix from a vector and set all other elements to 0. The source vector and this matrix must have the same underlying base type or a run time error will be generated.