正方行列の対角成分の和
\begin{align}
tr A = \sum_{i=1}^{n} a_{ii}
\end{align}
をトレースという。
今回はこれをC++で計算する。
実行結果
1,2,3,
4,5,6,
7,8,9,
15
ソースコード
#include <iostream>
void show(double*, int, int);
double Fnorm(double*, int, int);
double trace(double*, int, int);
int main() {
int m = 3, n = 3;
double sum = 0;
double* x;
x = new double[m * n];
for (int i = 0; i < m * n; i++) {
x[i] = i + 1;
}
show(x, n, m);
std::cout << std::endl;
std::cout << trace(x, n, m);
}
double Fnorm(double* x, int n, int m) {
double norm = 0;
for (int i = 0; i < n * m; i++) {
norm += std::pow(x[i], 2);
//std::cout << norm << std::endl;
}
std::cout << std::endl;
return std::sqrt(norm);
}
void show(double* x, int n, int m) {
int count = 0;
for (int i = 0; i < m * n; i++) {
count += 1;
std::cout << x[i] << ",";
if (count == m) {
std::cout << std::endl;
count = 0;
}
}
}
double trace(double* x, int n, int m) {
int sum = 0, pos = 0;
if (m != n) {
std::cout << "error" << std::endl;
return 0;
}
else {
for (int i = 0; i < m * n; i++) {
if (pos == i) {
sum += x[i];
pos += n + 1;
}
}
}
return sum;
}
コメント