The main objective of the algorithm is to read a txt file with the noise data information and calculate the covariance matrix and save it into an output file.
The program is:
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <TMatrixD.h>
#include <TPrincipal.h>
// Função para ler o arquivo e salvar os valores em uma matriz
std::vector<std::vector<double>> lerArquivo(const char* filename) {
std::ifstream file(filename);
std::vector<std::vector<double>> matriz;
if (file.is_open()) {
std::string linha;
while (std::getline(file, linha)) {
std::vector<double> valores;
std::istringstream iss(linha);
double valor;
while (iss >> valor) {
valores.push_back(valor);
}
matriz.push_back(valores);
}
file.close();
} else {
std::cout << "Erro ao abrir o arquivo." << std::endl;
}
return matriz;
}
// Função para calcular a matriz de covariância
TMatrixD calcularMatrizCovariancia(const std::vector<std::vector<double>>& dados) {
const int nLinhas = dados.size();
const int nColunas = dados[0].size();
TPrincipal principal(nColunas, "D");
for (int i = 0; i < nLinhas; i++) {
const double* linha = &dados[i][0];
principal.AddRow(linha);
}
principal.MakePrincipals();
TMatrixD covMatrix = *(principal.GetCovarianceMatrix());
return covMatrix;
}
// Função para salvar a matriz de covariância em um arquivo de texto
void salvarMatrizCovariancia(const TMatrixD& covMatrix, const char* filename) {
std::ofstream file(filename);
if (file.is_open()) {
for (int i = 0; i < covMatrix.GetNrows(); i++) {
for (int j = 0; j < covMatrix.GetNcols(); j++) {
file << covMatrix(i, j) << " ";
}
file << std::endl;
}
file.close();
} else {
std::cout << "Erro ao abrir o arquivo para salvar a matriz de covariância." << std::endl;
}
}
int main() {
const char* filename = "RuidoOcupacao_100.txt";
// Ler o arquivo e salvar os valores em uma matriz
std::vector<std::vector<double>> dados = lerArquivo(filename);
// Calcular a matriz de covariância dos dados
TMatrixD covMatrix = calcularMatrizCovariancia(dados);
// Salvar a matriz de covariância em um arquivo de texto
const char* outputFilename = "matriz_covariancia.txt";
salvarMatrizCovariancia(covMatrix, outputFilename);
std::cout << "Matriz de covariância salva em: " << outputFilename << std::endl;
return 0;
}
But the covariance matrix that I obtained is different in order of magnitude of the result I was expecting. I tried to chance the parameters “D” and “ND” but the result is the same. Somebody please have an idea how can I use the command GetCovarianceMatrix() in this case?