### calculate average of a diagonal line of complex matrix

Hi, I would like to calculate the average of the diagonal elements of a matrix. May I know which part that I need to do a correction? I have no idea why the division operation to compute average is not match.

One more thing, may I know why I cannot use all the buttons at the bottom of this box? I tried to insert the code using the <> button, but it failed.

Thank you.

//Add elements in a diagonal line of a matrix

#include <conio.h>
#include<iostream>
#include<cmath>
#include <complex>
#include <string>
#include <iomanip>
using namespace std;

//Main function
//All the operations is done here
int main(int argc, char** argv)
{
int order = 4;
int i, j;
complex <double> average= (0.0, 0.0);;
complex <double> d1sum = (0.0,0.0);
//complex <double> d2sum = (0.0, 0.0);

complex <double> Z[4][4] = { { 18.44 , -4.2 - 3.8i, 3.5 - 2.3i, 8.0 + 4.2i },
{ -4.2 - 3.8i, 20.5, 0.3 + 4.0i, 7.8 + 2.2i },{ 3.4 - 10.1i, 8.1 + 3.2i, 17.3, 6.2 - 1.8i },{ 0.3 + 3.8i, 10.4 - 12.1i, 5.4 - 8.4i, 26.3 } };

for (i = 0; i < order; i++)
{
for (j = 0; j < order; j++)
{

if (i == j)
d1sum = d1sum + Z[i][j];

//if (i + j == (order - 1))
// d2sum = (d2sum + Z[i][j]);

}

cout << "\nSum of 1st diagonal is " << d1sum;
//cout << "\nSum of 2st diagonal is " << d2sum;
}

average = d1sum / order;
cout << "average is " << average;
//cout << "\n";
system("pause");
return 0;
}

Error:
no operator "/" matches these operands add_diag

Last edited on
first, did you really just do an order*order loop to do one row's worth of work?
for(i = 0; i< order; i++)
sum += m[i][i];

I think you just need
complex<double> den(order,0.0);
average = d1sum/den;
or some sort of cast may make it work. Though I would have thought it knew how to divide complex by int... not sure ... try that to see if it works?
Last edited on
`average = d1sum / (double)order;`

Also, as @Jonnin said, you only need a single loop over i to sum the diagonal elements Z[i][i].

You can retrospectively edit your post to put code tags around it.

When you have done that, please remove the unnecessary conio.h and we will be able to run your code in cpp.sh.
lawl. I was caught up in the <complex> and missed the (int) issue, with no excuse.
Last edited on
Thank you so much . It works.
Registered users can post here. Sign in or register to post.