void GnuplotWriter::writeMatrixGnuplot(const Matrix& m, const string& file, bool columnWise) { ofstream os(file.c_str()); // "Column-wise" Gnuplot output. if (columnWise) { for (unsigned int j = 0; j < m.cols(); ++j) { os << j << "\t"; for (unsigned int i = 0; i < m.rows(); ++i) { os << m.at(i, j); if (i < m.rows() - 1) os << "\t"; } os << endl; } } // "Row-wise" Gnuplot output. else { for (unsigned int i = 0; i < m.rows(); ++i) { os << i << "\t"; for (unsigned int j = 0; j < m.cols(); ++j) { os << m.at(i, j); if (j < m.cols() - 1) os << "\t"; } os << endl; } } }
/* * A series of rotations can be used to zero a row if its diagonal entry is zero * Golub and Van Loan 1996 gives the following method */ static void eliminateBeta(Matrix& J, Matrix& U, Matrix& V, int p, int q, int k) { const int m = J.rows(), n = J.cols(); const int N = n - q; double cs, sn; if (k + 1 < N) { Matrix S; for (int i = k + 1; i < N; i++) { rot(J.at(k, i), J.at(i, i), cs, sn); S = givensCS(m, k, i, sn, cs); J = S * J; U = U * S.trans(); } } else { Matrix T; for (int i = k - 1; i >= 0; i--) { if (rot(J.at(i, i), J.at(i, k), cs, sn) < 0) { cs = -cs; sn = -sn; } T = givensCS(n, i, k, cs, sn); J = J * T; V = V * T; } } }
Vector Statistics::getRegressionModelCoefficients(const Vector &functionValues, const Matrix &modelArguments) { Matrix modelArgumentsWide = modelArguments; qint32 N = functionValues.count(); modelArgumentsWide << Vector().fill(1.0, N); for (Matrix::ConstIterator regressor = modelArgumentsWide.constBegin(); regressor != modelArgumentsWide.constEnd(); ++regressor) Q_ASSERT(regressor->count() == N); Matrix m; for (qint32 i = 0; i < modelArgumentsWide.count(); ++i) { Vector line; for (qint32 j = 0; j < modelArgumentsWide.count(); ++j) { qreal S(0); for (qint32 k = 0; k < N; ++k) S += qPow(modelArgumentsWide.at(i).at(k), modelArguments.count()) * modelArgumentsWide.at(j).at(k); line << S; } qreal S(0); for (qint32 k = 0; k < N; ++k) S += functionValues.at(k) * qPow(modelArgumentsWide.at(i).at(k), modelArguments.count()); line << S; m << line; } LinearSystemSolver solver; return solver.solve(m); }
/* * Compute singular value decomposition by GR-SVD * Matrix is bidiagonalized by Golub and Kahan, * then deflated by QR iteration. * Reference: Handbook of Linear Algebra, CRC press, 2007 ed. */ Matrix Matrix::svd(Matrix& U, Matrix& V, bool reorder) const { const double eps = DBL_EPSILON; const int m = nr, n = nc; //Perform Golub-Kahan bidiagonalization Matrix J = bidiag(U, V); int i, p, q; while (true) { //Test for beta-convergence for (i = 0; i < n - 1; i++) if (dabs(J.at(i, i + 1)) <= eps * (dabs(J.at(i, i)) + dabs(J.at(i + 1, i + 1)))) J.at(i, i + 1) = 0.0; //Block the matrix into a diagonal, a strictly bidiagonal, and a remainder block pqBlock(J, p, q); //Test if the entire matrix is diagonal if (q == n) break; //Determine a set of rotations to perform for (i = p; i < n - q; i++) if (J.at(i, i) == 0.0) { eliminateBeta(J, U, V, p, q, i);//This set of rotations eliminates one superdiagonal value break; } if (i == n - q) chase(J, U, V, p, q);//This set of rotations decreases the superdiagonal values towards convergence } if (reorder) reorderSVD(U, J, V); return J; }
bool test() { Matrix m1(2, 3); Matrix m2(3, 2); m1.at(0, 0) = 1; m1.at(0, 1) = 2; m1.at(0, 2) = 0; m1.at(1, 0) = 4; m1.at(1, 1) = 3; m1.at(1, 2) = -1; m2.at(0, 0) = 5; m2.at(0, 1) = 1; m2.at(1, 0) = 2; m2.at(1, 1) = 3; m2.at(2, 0) = 3; m2.at(2, 1) = 4; Matrix r = Matrix::product(m1, m2); assert(r.m() == 2); assert(r.n() == 2); assert(r.at(0, 0) == 9); assert(r.at(0, 1) == 7); assert(r.at(1, 0) == 23); assert(r.at(1, 1) == 9); return true; }
static void swapColumns(Matrix& A, int i, int j) { double t; for (int k = 0; k < A.rows(); k++) { t = A.at(k, i); A.at(k, i) = A.at(k, j); A.at(k, j) = t; } }
double getScalarPr(const Matrix& a,const Matrix& b) { double res = 0; for (unsigned i = 0; i < a.GetSizeX(); i++) { res += a.at(0,i)+b.at(0,i); } return res; }
/* * Divide the matrix into three blocks: * [ B1,1 0 0 ] p rows * [ 0 B2,2 0 ] n - q - p rows * [ 0 0 B3,3 ] q rows * B3,3 is the largest strictly diagonal block, hence q is maximized * B2,2 is the largest strictly bidiagonal block, hence p is minimized * Each pass of the Golub-Reinsch QR operates on B2,2. */ static void pqBlock(const Matrix& J, int& p, int& q) { const int n = J.cols(); //B3,3 (q x q) is the largest diagonal at the bottom-right of J for (q = 0; q < n - 1 && J.at(n - q - 2, n - q - 1) == 0.0; q++); if (q == n - 1) q = n; //B1,1 (p x p) is constructed so that B2,2 is the largest strictly bidiagonal block for (p = n - q - 1; p > 0 && J.at(p - 1, p) != 0.0; p--); if (p < 0) p = 0; }
Matrix bruteForceMultiplication(const Matrix &A, const Matrix &B) { Matrix C; C.alloc(A.N, B.M); for (int k = 0; k < A.M; ++k) for (int i = 0; i < A.N; ++i) for (int j = 0; j < B.M; ++j) C.at(i, j) += A.at(i, k) * B.at(k, j); return C; }
int minmult( Matrix<uint> &M, Matrix<uint> &P, const vector<uint> &d, uint i, uint j ) { if(M.at(i,j) != INF) { return M.at(i,j); } if(i == j) { M.at(i,j) = 0; return M.at(i,j); } for(uint k = i; k<= j-1; k++) { uint cost = minmult(M, P, d, i, k) + minmult(M, P, d, k+1, j) + d.at(i-1)*d.at(k)*d.at(j); if(cost < M.at(i,j)) { M.at(i,j) = cost; P.at(i,j) = k; } } return M.at(i,j); }
static void reorderSVD(Matrix& U, Matrix& W, Matrix& V) { const int m = U.rows(), n = V.rows(); int i, j, k; for (i = 0; i < n - 1; i++) { k = i; for (j = i + 1; j < n; j++) if (dabs(W.at(j, j)) > dabs(W.at(k, k))) k = j; if (i != k) { swapColumns(U, i, k); swapDiag(W, i, k); swapColumns(V, i, k); } } }
Matrix strassenMultiplication(const Matrix &L, const Matrix &R) { int N = L.N; if (N <= 64) return bruteForceMultiplication(L, R); Matrix A[2][2], B[2][2], C[2][2]; for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) { A[i][j].alloc(N / 2, N / 2); B[i][j].alloc(N / 2, N / 2); C[i][j].alloc(N / 2, N / 2); for (int x = 0; x < N / 2; ++x) for (int y = 0; y < N / 2; ++y) { A[i][j].at(x, y) = L.at(i * N / 2 + x, j * N / 2 + y); B[i][j].at(x, y) = R.at(i * N / 2 + x, j * N / 2 + y); } } Matrix M1 = strassenMultiplication(A[0][0] + A[1][1], B[0][0] + B[1][1]), M2 = strassenMultiplication(A[1][0] + A[1][1], B[0][0]), M3 = strassenMultiplication(A[0][0], B[0][1] - B[1][1]), M4 = strassenMultiplication(A[1][1], B[1][0] - B[0][0]), M5 = strassenMultiplication(A[0][0] + A[0][1], B[1][1]), M6 = strassenMultiplication(A[1][0] - A[0][0], B[0][0] + B[0][1]), M7 = strassenMultiplication(A[0][1] - A[1][1], B[1][0] + B[1][1]); C[0][0] = M1 + M4 - M5 + M7; C[0][1] = M3 + M5; C[1][0] = M2 + M4; C[1][1] = M1 - M2 + M3 + M6; Matrix solution; solution.alloc(N, N); for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) for (int x = 0; x < N / 2; ++x) for (int y = 0; y < N / 2; ++y) solution.at(i * N / 2 + x, j * N / 2 + y) = C[i][j].at(x, y); return solution; }
Matrix Matrix::operator*(const Matrix& mat) const { Matrix result(nr, mat.nc); for (int r = 0; r < result.nr; r++) for (int c = 0; c < result.nc; c++) for (int i = 0; i < nc; i++) result.at(r, c) += at(r, i) * mat.at(i, c); return result; }
void print_matrix(const Matrix<char>& m) { for (int y = 0; y < m.height(); y++) { for (int x = 0; x < m.width(); x++) { cout << m.at(x, y) << ' '; } cout << endl; } }
Matrix Matrix :: operator+(const Matrix &m) const //Matrix Matrix :: operator+(Matrix &m) { //int size = m.giveNumberOfRows(); Matrix result; result.resize( this->nRows, this->nColumns); for ( int i = 1; i<=nRows; i++){ for ( int j = 1; j<=nColumns; j++){ result.at(i,j) = this->at(i,j) + m.at(i,j); } } return result; }
// Solves the discrete poisson equation using the SOR method std::pair<unsigned, REAL> SOR_Poisson(const Config::geo& geoConfig, const Config::solver solverConfig, const Geometry& geometry, Matrix& P, const Matrix& rhs) { // comupte initial residual REAL res = comp_res(geoConfig, geometry, P, rhs); const REAL omega = solverConfig.omega; const REAL delx2 = geoConfig.delx*geoConfig.delx; const REAL dely2 = geoConfig.dely*geoConfig.dely; const auto& fluid = geometry.get_fluid(); unsigned it = 0, i=0, j=0; for(it = 1; it<solverConfig.itmax && res>solverConfig.eps; ++it) { updatePressureBoundary(geoConfig, geometry, P); // compute next iteration for(const auto& cell : fluid){ i=cell.first; j=cell.second; P.at(i,j) = (1-omega)*P.at(i,j) + omega/(2*(1/delx2 + 1/dely2)) *((P.at(i+1,j)+P.at(i-1,j))/delx2 + (P.at(i,j+1)+P.at(i,j-1))/dely2 - rhs.at(i,j)); } // compute residual res = comp_res(geoConfig, geometry, P, rhs); } return std::make_pair(it, res); }
const T Trace(const Matrix <N, N, T, MOD> &st ) { T value = T(0); for ( size_t i = 0; i < N; ++i ) value = st.mod( value + st.at( i, i ) ); return value; }
Matrix<double, 2, 2> makeCholeskyDecomp() const { double cov; Matrix<double, 2, 2> propMatrix; /* compute Cholesky decomposition of covariance matrix */ gsl_matrix *covMat = gsl_matrix_alloc (2, 2); const double cholScale = 1000; /* for numerical stability */ { cov = gsl_stats_covariance (params.at(0).data(), 1, params.at(0).data(), 1, params.at(0).size()); gsl_matrix_set (covMat, 0, 0, cov * cholScale * cholScale); } { cov = gsl_stats_covariance (params.at(1).data(), 1, params.at(0).data(), 1, params.at(1).size()); gsl_matrix_set (covMat, 1, 0, cov * cholScale * cholScale); gsl_matrix_set (covMat, 0, 1, cov * cholScale * cholScale); } { cov = gsl_stats_covariance (params.at(1).data(), 1, params.at(1).data(), 1, params.at(1).size()); gsl_matrix_set (covMat, 1, 1, cov * cholScale * cholScale); } /* Cholesky decomposition */ if (gsl_linalg_cholesky_decomp (covMat)) { // Handle a potential error. // As far as I know, this will always be due to a // non-positive definite matrix. throw NonPositiveDefiniteMatrix("Non-positive matrix in makeCholeskyDecomp"); } /* compute proposal matrix from Cholesky factor */ /* Gelman, Roberts, Gilks scale */ double GRGscale = 2.38 / sqrt(2); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { if (j <= i) { propMatrix.at(i).at(j) = GRGscale * gsl_matrix_get (covMat, i, j) / cholScale; } } } gsl_matrix_free (covMat); return propMatrix; }
Matrix operator *(const double& a, const Matrix& mat) { Matrix multiplyMat(mat.cols(), mat.rows()); for (int i = 0; i < mat.rows(); i++) { for (int j = 0; j < mat.cols(); j++) { multiplyMat.at(i, j) = a*mat.at(i, j); } } return multiplyMat; }
Matrix* SlidingWindowTransform::inverseTransform(Matrix* spectrogram) const { unsigned int nCols = (spectrogram->cols() - 1) * _frameRate + _frameSize; Matrix* output = new Matrix(spectrogram->rows() / _frameSize, nCols); if (output->rows() * _frameSize != spectrogram->rows()) { throw Poco::InvalidArgumentException("Invalid matrix dimensions: " "input matrix has " + Poco::NumberFormatter::format(spectrogram->rows()) + " rows, not a multiple of frame size = " + Poco::NumberFormatter::format(_frameSize)); } output->zero(); std::vector<int> counts(output->cols(), 0); unsigned int outputCol = 0; for (unsigned int inputCol = 0; inputCol < spectrogram->cols(); ++inputCol, outputCol += _frameRate) { unsigned int outputColOffset = 0; unsigned int outputRow = 0; for (unsigned int inputRow = 0; inputRow < spectrogram->rows(); ++inputRow) { outputColOffset = inputRow / output->rows(); // integer division outputRow = inputRow % output->rows(); output->at(outputRow, outputCol + outputColOffset) += spectrogram->at(inputRow, inputCol); counts[outputCol + outputColOffset]++; } } // interpolation for (unsigned int j = 0; j < output->cols(); ++j) { int cnt = counts[j] / output->rows(); // integer division //cout << "j = " << j << " cnt = " << cnt << endl; for (unsigned int i = 0; i < output->rows(); ++i) { output->at(i, j) /= (double)cnt; } } return output; }
void PrintPath(Matrix& Solution, Matrix Path, Matrix Nodes, int i, int j) { int k=i, l=j; while ((i>=0) && (j>=0)) { Solution.at(i,j) = Nodes.at(i,j); if (Path.at(i,j) == 0) j--; else i--; } cout << "The best path is:" << endl; for (int a=0;a<=k;a++) { for (int b=0;b<=l;b++) cout << Solution.at(a,b) << " "; cout << endl; } }
constexpr auto operator()(Matrix m) const { return eval_if(m.size() == int_<1>, always(m.at(int_<0>, int_<0>)), [=](auto _) { auto cofactors_1st_row = unpack(_(range)(int_<0>, m.ncolumns()), on(list, partial(cofactor, m, int_<0>)) ); return scalar_prod(head(rows(m)), cofactors_1st_row); } ); }
Matrix<float> MyImage::getGrayscaleMatrix(){ Image * magick_image = getMagickImage(); size_t width, height; width = magick_image->columns(); height = magick_image->rows(); Matrix<float> grayscale (width, height); for(size_t x = 0; x < width; ++x){ for(size_t y = 0; y < height; ++y){ grayscale.at(x,y) = ((ColorGray) magick_image->pixelColor(x,y)).shade(); } } return grayscale; }
double Kmedoid::determineClosestMedoids(const Matrix& distMatrix) { double cost = 0; for(uint i = 0; i < distMatrix.size(); ++i) { double minDist = std::numeric_limits<double>::max(); uint clusterId = std::numeric_limits<uint>::max(); for(uint j = 0; j < m_medoids.size(); ++j) { if(distMatrix.at(i).at(m_medoids.at(j)) < minDist) { minDist = distMatrix.at(i).at(m_medoids.at(j)); clusterId = j; } } m_clusterId.at(i) = clusterId; cost += minDist; } return cost; }
vector<double> GradientDescent::extremum(const vector<double> &start_point, const vector<vector<double>> &c, const vector<double> &d, EType type) { vector<double> gr; // gradient vector<double> res = start_point; Matrix mat; // matrix of active constraints bool found = false; int iterations = 0; while (!found) { gr = gradient(res); mat = getActiveConstraints(c, d, res); // constraints, where sum = di if (mat.size().first != 0) // there are some active constraints { //project gradient onto this area mat = mat.transpose() * (mat * mat.transpose()).inverse() * mat; mat = Matrix::E(mat.size().first) - mat; mat = Matrix(gr) * mat; } else mat = gr; // use gradient for (uint i = 0; i < res.size(); i++) // go to the direction of projection of gradient(antigradient if miminization) if (type == EType::Maximun) res[i] += step*mat.at(0, i); else res[i] -= step*mat.at(0, i); found = vectorNorm(gr) < stoppingE || ++iterations > max_iterations; } return res; }
void Matrix :: bePositiveDefiniteMatrix(int n) { Matrix tmp; tmp.resize(n,n); double s=0; this->beRandomMatrix(n); this->beSymmetricPart(); for ( int i = 1; i <= n; i++ ){ for ( int j = i; j <= n; j++){ s = 0; for ( int k = 1; k <= n; k++ ) { s += this->at(i,k) * this->at(k,j); } tmp.at(i,j) = s; tmp.at(j,i) = s; } } for ( int i = 1; i <= n; i++ ){ for ( int j = 1; j <= n; j++){ this->at(i,j) = tmp.at(i,j); } } }
void Vector :: beTestRhsVector(Matrix &A) { int n = A.giveNumberOfRows(); Vector tmp; tmp.resize(n); tmp.setToOnes(); this->resize(n); for ( int i = 1; i<=n; i++){ for ( int j = 1; j<=n; j++){ this->at(i) += A.at(i,j)*tmp.at(j); } } }
Matrix Matrix::solveNull(Matrix A) { //Row echelon form double factor; for (int k = 0; k < A.nr; k++) { //Find highest pivot int highest = k; for (int i = k + 1; i < A.nr; i++) if (dabs(A.at(i, k)) > dabs(A.at(highest, k))) highest = i; A.permuteRows(highest, k); //Scale row for (int i = k + 1; i < A.nr; i++) { if (A.at(k, k) == 0.0 || A.at(i, k) == 0.0) continue; factor = -A.at(i, k) / A.at(k, k); for (int j = k; j < A.nc; j++) A.at(i, j) += factor * A.at(k, j); } } //Basic vs free variables int* freevars = new int [A.nc], nfree = 0; for (int r = 0, c = 0; r < A.nr && c < A.nc; c++) if (A.at(r, c) == 0.0) freevars[nfree++] = c; else r++; //Reconstruct the matrix to allow fixing the free variables Matrix M(A.nc, A.nc), N(A.nc, nfree), zero(A.nc, 1); M.replace(A, 0, 0); for (int i = 0; i < nfree; i++) M.at(freevars[i], freevars[i]) = 1.0; //Fix each free variable and solve for the null vector bases for (int i = 0; i < nfree; i++) { zero.at(freevars[i]) = 1.0; N.replace(solve(M, zero), 0, i); zero.at(freevars[i]) = 0.0; } delete [] freevars; return N; }
void order(uint i, uint j, const Matrix<uint> &P) { if(i == j ) { cout << "A" << i; } else { uint k = P.at(i,j); cout << "("; order(i,k, P); order(k+1, j, P); cout << ")"; } }
RowVector RowVector::operator * (const Matrix& m) const { debug_assert(_dim == m.rows()); // TODO: Make use of ATLAS if possible. RowVector result(m.cols()); for (unsigned int i = 0; i < m.cols(); i++) { result(i) = 0; for (unsigned int j = 0; j < _dim; j++) { result(i) += this->at(j) * m.at(j,i); } } return result; }