|
发表于 2020-2-15 08:13:36
|
显示全部楼层
https://blog.csdn.net/zjxxyz123/article/details/79049579
/* 矩阵的求逆(借鉴他人) */
/* Uses Gauss-Jordan elimination.
The elimination procedure works by applying elementary row
operations to our input matrix until the input matrix is reduced to
the identity matrix.
Simultaneously, we apply the same elementary row operations to a
separate identity matrix to produce the inverse matrix.
If this makes no sense, read wikipedia on Gauss-Jordan elimination.
This is not the fastest way to invert matrices, so this is quite
possibly the bottleneck. */
int destructive_invert_matrix(Matrix input, Matrix output) {
int i;
int j;
int r;
double scalar;
double shear_needed;
assert(input.rows == input.cols);
assert(input.rows == output.rows);
assert(input.rows == output.cols);
set_identity_matrix(output);
/* Convert input to the identity matrix via elementary row operations.
The ith pass through this loop turns the element at i,i to a 1
and turns all other elements in column i to a 0. */
for ( i = 0; i < input.rows; ++i) {
if (input.data[i][i] == 0.0) {
/* We must swap rows to get a nonzero diagonal element. */
for (r = i + 1; r < input.rows; ++r) {
if (input.data[r][i] != 0.0) {
break;
}
}
if (r == input.rows) {
/* Every remaining element in this column is zero, so this
matrix cannot be inverted. */
return 0;
}
swap_rows(input, i, r);
swap_rows(output, i, r);
}
/* Scale this row to ensure a 1 along the diagonal.
We might need to worry about overflow from a huge scalar here. */
scalar = 1.0 / input.data[i][i];
scale_row(input, i, scalar);
scale_row(output, i, scalar);
/* Zero out the other elements in this column. */
for ( j = 0; j < input.rows; ++j) {
if (i == j) {
continue;
}
shear_needed = -input.data[j][i];
shear_row(input, j, i, shear_needed);
shear_row(output, j, i, shear_needed);
}
}
return 1;
}
|
|