Read element in diagonal

I have an array 3x1:
P[0]=3;
P[1]=0;
P[2]=2;

what i want is, i want to call this element as diagonal element for 3x3 matrix such as

3 0 0
0 3 0
0 0 3

I'm using code for identity matrix and applied with my case
but the result is

0 0 0
0 0 0
0 0 0

i'm thinking of multiply identity matrix with the element of P, but it looks like more loop fucntion will involve

#include <fstream>
#include <iostream>
#include <iomanip>


#define M 3

using namespace std;

int main()
{
int i, j,k,q;
double G[M][M],P[M],L[M][M],Q[M][M];

G[0][0] = 3;
G[0][1] = 6;
G[0][2] = -8;


G[1][0] = 0;
G[1][1] = 0;
G[1][2] = 6;


G[2][0] = 0;
G[2][1] = 0;
G[2][2] = 2;

cout <<"Matrix A:" <<endl;

for (i=0;i<=M-1;i++)
{
for (j=0;j<=M-1;j++)
{
cout << setw(7) << G[i][j] << " ";
}
cout << endl;
}


cout << "The eigenvalue are:" << endl;
for (i = 0; i <= M-1 ; i++)
{
for (j = 0; j <= M-1 ; j++)
{
if (i == j)
{
P[i] = 0;
cout << "P[" << i << "] = " << G[i][j] << endl;
}
}
cout << endl;
}

//applied identity matrix code

cout << "Eigenvalue in matrix form:" << endl;
for (i = 0; i <= M - 1; i++)
{
for (j = 0; j <= M - 1; j++)
{
if (i == j)
{
L[i][j] = P[i];
L[i][j] = 0;
cout <<L[i][j]<< " ";


}

else
{
L[i][j] = 0;
cout << L[i][j] << " ";
}

}
cout << endl;
}


cin.get();




}
You have two successive lines
1
2
L[i][j] = P[i];
L[i][j] = 0;


Whatever you put in the first line will be immediately updated by the second ... and hence will be zero ... which is what you get.

Beyond this, I don't understand from your explanation what you are trying to do. If these are the eigenvalues of your matrix and you want to put them on the diagonal of the matrix (usually denoted D) then first create a zero matrix, then update the [i][i] diagonal component, looping on i only. (If, alternatively, you wanted the transformation matrix, then the eigenvectors are the columns.)
Last edited on
yes, i want to put the eigenvalues on the diagonal of the matrix, I set my eigenvalues as P[i] and i want to call them separately such as
1
2
3
P[i] 0 0
0 P[i] 0
0 0 P[i]

i should try update the diagonal component first :)
Last edited on
Please use code tags. http://www.cplusplus.com/articles/jEywvCM9/
You can edit your post, highlight your code and click the <> button on the right.

1
2
3
for( int i{}; i < M; i++ ) {
      L[i][i] = /* ... */
}
Thanks!!my problem is solved!!*<insert happy face>
Topic archived. No new replies allowed.