【发布时间】:2012-02-27 00:53:32
【问题描述】:
下面的代码计算给定协方差矩阵的相关矩阵。我怎样才能写得更好?问题是这部分代码将在尺寸约为 100 x 100 的矩阵上运行 1000 次。
// Copy upper triangle of covariance matrix to correlation matrix
for(i = 0; i < rows; i++){
for(j = i; j < rows; j++){
corrmatrix.array[i * rows + j] = covmatrix.array[i * rows + j];
}
}
// Calculate upper triangle of corr matrix
for(i = 0; i < rows; i++){
root = sqrt(covmatrix.array[(i * rows) + i]);
for(j = 0; j <= i; j++){ // Move down
corrmatrix.array[ j * rows + i ] /= root;
}
k = i * rows;
for(j = i; j < rows; j++){ // Move across
corrmatrix.array[ k + j ] /= root;
}
}
// Copy upper triangle to lower triangle
for(i = 0; i < rows; i++){
k = i * rows;
for(j = i; j < rows; j++){
corrmatrix.array[ (j * rows) + i ] = corrmatrix.array[ k + j ];
}
}
我已经检查了行和列是否相等等,所以我只是在任何地方都使用行。我想优化速度(显着)。
PS:
- 矩阵以行优先的密集格式存储
- 我暂时不使用打包存储。
谢谢
【问题讨论】:
标签: c performance numerical