SEXP kz2d(SEXP x, SEXP window, SEXP iterations) { int i, j, k; SEXP ans, tmp, dim; int nr, nc; int m1, m2; if (length(window)<2) {m1 = m2 = INTEGER_VALUE(window);} else {m1 = INTEGER(window)[0]; m2 = INTEGER(window)[1];} dim = GET_DIM(x); nr = INTEGER(dim)[0]; nc = INTEGER(dim)[1]; PROTECT(ans = allocMatrix(REALSXP, nr, nc)); PROTECT(tmp = allocMatrix(REALSXP, nr, nc)); copyMatrix(tmp, x, 0); for(k=0; k<INTEGER_VALUE(iterations); k++) { for(j=0;j<nc;j++) { for(i=0;i<nr; i++) { REAL(ans)[i+nr*j] = mavg2d(tmp, i, j, m1, m2); } } /* copyMatrix (destination, source, byrow) */ copyMatrix(tmp, ans, 0); } UNPROTECT(2); return ans; }
void graphics::pushMatrix() { switch (matrixMode) { case SINNCA_MODELVIEW_MATRIX: { copyMatrix(&modelViewStack[modelViewIndex+1], &modelViewStack[modelViewIndex]); ++modelViewIndex; break; } case SINNCA_PROJECTION_MATRIX: { copyMatrix(&projectionStack[projectionIndex+1], &projectionStack[projectionIndex]); ++projectionIndex; break; } case SINNCA_TEXTURE_MATRIX: { copyMatrix(&textureStack[textureIndex+1], &textureStack[textureIndex]); ++textureIndex; break; } } }
void multiplyRotationMatrix(matrix a, matrix eigen_vectors, int i, int j, int size) { double C = a[i][j]; double F = (a[j][j] - a[i][i])/2; double t; if (F > 0) t = -C/(F + sqrt(F*F + C*C)); else t = -C/(F - sqrt(F*F + C*C)); double c = 1/sqrt(1 + t*t); double s = t * c; matrix b, sv; copyMatrix(b, a, size); for (int l = 0; l < size; l++) { b[i][l] = s * a[j][l] + c * a[i][l]; b[j][l] = c * a[j][l] - s * a[i][l]; } copyMatrix(a, b, size); for (int l = 0; l < size; l++) { a[l][i] = s * b[l][j] + c * b[l][i]; a[l][j] = c * b[l][j] - s * b[l][i]; } copyMatrix(sv, eigen_vectors, size); for (int l = 0; l < size; l++) { sv[l][i] = s * eigen_vectors[l][j] + c * eigen_vectors[l][i]; sv[l][j] = c * eigen_vectors[l][j] - s * eigen_vectors[l][i]; } copyMatrix(eigen_vectors, sv, size); }
Matrix4f Camera::getRotationM() { Matrix4f xRot, yRot, zRot, m_identity, result; m_identity = getIdentity(); /* get the rotation radians about each axis */ const float xRads = ToRadian(xRotation); const float yRads = ToRadian(yRotation); const float zRads = ToRadian(zRotation); /* rotate around the x axis */ copyMatrix(xRot, m_identity); xRot.m[1][1] = cosf(xRads); xRot.m[1][2] = -sinf(xRads); xRot.m[2][1] = sinf(xRads); xRot.m[2][2] = cosf(xRads); /* rotate around the y axis */ copyMatrix(yRot, m_identity); yRot.m[0][0] = cosf(yRads); yRot.m[0][2] = -sinf(yRads); yRot.m[2][0] = sinf(yRads); yRot.m[2][2] = cosf(yRads); /* rotate around the z axis*/ copyMatrix(zRot, m_identity); zRot.m[0][0] = cosf(zRads); zRot.m[0][1] = -sinf(zRads); zRot.m[1][0] = sinf(zRads); zRot.m[1][1] = cosf(zRads); result = (yRot * xRot * zRot); return result; }
SEXP rma_c_complete_copy(SEXP PMmat, SEXP ProbeNamesVec,SEXP N_probes, SEXP norm_flag, SEXP bg_flag, SEXP bg_type, SEXP verbose){ SEXP dim1,PMcopy,exprs; int rows,cols; double *PM; if (INTEGER(bg_flag)[0]){ if (INTEGER(verbose)[0]){ Rprintf("Background correcting\n"); } PROTECT(dim1 = getAttrib(PMmat,R_DimSymbol)); rows = INTEGER(dim1)[0]; cols = INTEGER(dim1)[1]; PROTECT(PMcopy = allocMatrix(REALSXP,rows,cols)); PM = NUMERIC_POINTER(PMcopy); copyMatrix(PMcopy,PMmat,0); rma_bg_correct(PM, rows, cols); exprs = rma_c_call(PMcopy, ProbeNamesVec, N_probes, norm_flag, verbose); UNPROTECT(2); return exprs; } else { PROTECT(dim1 = getAttrib(PMmat,R_DimSymbol)); rows = INTEGER(dim1)[0]; cols = INTEGER(dim1)[1]; PROTECT(PMcopy = allocMatrix(REALSXP,rows,cols)); copyMatrix(PMcopy,PMmat,0); exprs = rma_c_call(PMcopy, ProbeNamesVec, N_probes, norm_flag, verbose); UNPROTECT(2); return exprs; } }
void KinematicMotion::matrixTanspose(double *M) { double MCopy[9]; copyMatrix(M, MCopy); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) MCopy[i * 3 + j] = M[j * 3 + i]; copyMatrix(MCopy, M); }
void findSolution(unsigned n) /* Построява таблицата */ { unsigned i; m[1][1] = 0; for (i = 1; i <= n; i <<= 1) { copyMatrix(i + 1, 1, i, i); copyMatrix(i + 1, i + 1, i, 0); copyMatrix(1, i + 1, i, i); } }
m3* graphics::getNormalMatrix() { m4 matrix; copyMatrix(&matrix, getModelMatrix()); invert(&matrix); transpose(&matrix); copyMatrix(&normalMatrix, &matrix); return &normalMatrix; }
void convergeMatrix(Matrix *matrix) { Matrix *originalCopy = copyMatrix(matrix); Matrix *copy; int n = 1; do { copy = copyMatrix(matrix); multiplyMatrix(matrix, copy, originalCopy); n++; } while(keepConverging(n, matrix, copy)); }
void levelSet3D(MATRIXD im, MATRIX init_mask, int max_its, double E, double T, double alpha, MATRIX *seg0, MATRIX *tmap, MATRIXD *phi, long **ls_vols){ // some of these variables will be used as the local variables for other functions // they are defined outside (like global variables) because we want to decrease the overhead // corresponding to allocation and deallocation (since we have multiple calls for the same function long dx = im.dx, dy = im.dy, dz = im.dz; int *px, *py, *pz, *qx, *qy, *qz, k, tmap_it = 1; MATRIX intTmp; MATRIXD dblTmp = allocateMatrixD(dx,dy,dz); MATRIXD gradPhi = allocateMatrixD(dx,dy,dz); *phi = allocateMatrixD(dx,dy,dz); *seg0 = allocateMatrix(dx,dy,dz); *tmap = allocateMatrix(dx,dy,dz); *ls_vols = (long *)calloc(max_its,sizeof(long)); // initialized with 0 initializeMatrix(tmap,0); initializeGlobals4bwdist(dx,dy,dz,&px,&py,&pz,&qx,&qy,&qz,&intTmp); createSignedDistanceMap(init_mask,phi,px,py,pz,qx,qy,qz,intTmp,dblTmp); // temps: intTmp, dblTmp for (k = 1; k <= max_its; k++){ calculateCurvature(*phi,&dblTmp,0,dx-1,0,dy-1,0,dz-1); // dblTmp keeps the curvatures calculateF(im,dblTmp,&dblTmp,E,T,alpha,0,dx-1,0,dy-1,0,dz-1); // first dblTmp (input): curvatures, second dblTmp (output): F values calculateGradPhi(*phi,dblTmp,&gradPhi,0,dx-1,0,dy-1,0,dz-1); evolveCurve(phi,dblTmp,gradPhi,0,dx-1,0,dy-1,0,dz-1); if (k % 50 == 0) reinitializeDistanceFunction(phi,init_mask,px,py,pz,qx,qy,qz,intTmp,dblTmp); // temps: init_mask, intTmp, dblTmp (*ls_vols)[k-1] = selectNonpositive(*phi,&intTmp,0,dx-1,0,dy-1,0,dz-1); if (k == 1){ selectNonpositive(*phi,seg0,0,dx-1,0,dy-1,0,dz-1); copyMatrix(tmap,*seg0); } else if (k % 10 == 0){ selectNonpositive(*phi,&intTmp,0,dx-1,0,dy-1,0,dz-1); updateMaps(tmap,intTmp,*seg0,tmap_it,0,dx-1,0,dy-1,0,dz-1); copyMatrix(seg0,intTmp); tmap_it++; } } selectNonpositive(*phi,seg0,0,dx-1,0,dy-1,0,dz-1); freeMatrixD(gradPhi); freeMatrixD(dblTmp); freeGlobals4bwdist(px,py,pz,qx,qy,qz,intTmp); }
int main(int argc, char const *argv[]) { unsigned D; // Numero de paginas. (Dimensão da matriz) double dampingFactor; // Fator de Damping double **matriz = NULL; // Matriz a ser alocada. double **saida = NULL; // Matriz de saida. unsigned i, j; // Posições onde a matriz sera setada para 1 scanf("%u %lf", &D, &dampingFactor); matrixAlloc(&matriz, D, D); while (scanf("%u %u", &i, &j) == 2) { matriz[i][j] = 1; } stochasticMatrix(matriz, D, D); dampMatrix(matriz, dampingFactor, D, D); copyMatrix(&saida, matriz, D, D); expontiationUntilConverge(&saida, matriz, D, 0); printIndexedVector(saida[0], D); matrixFree(saida, D); matrixFree(matriz, D); return 0; }
int main(int argc, char **argv) { // generate seed srand(time(NULL)); if (argc != 2) { printf("You did not feed me arguments, I will die now :( ... \n"); printf("Usage: %s [matrix size] \n", argv[0]); return 1; } int matrixSize = atoi(argv[1]); // Generate random SPD matrix double** A = initialize(0, 10, matrixSize); /*printf("Chol matrix\n"); print(A, matrixSize);*/ double **L = initialize(0, 10, matrixSize); //Testing OpenMpi Program copyMatrix(A,L,matrixSize); cholMPI(A,L, matrixSize, argc, argv); // Warning: cholMPI() acts directly on the given matrix L }
/*=========================================================================== * powerMethod * This algorithm determines the largest eigenvalue of a matrix using the * power method. * * This was described to me in a Randomized Algoirthms course. *=========================================================================*/ double powerMethod(matrix* a) { matrix* x; matrix* xp1; // x plus 1 const double EPSILON = 0.001; double sum; int i; int k = 0; int converge; assert(a->width == a->height, "Matrix must be square."); srand(time(0)); // Initalize our RNG // Let's initalize x to a random vector x = makeMatrix(1, a->height); for (i = 0; i < a->height; i++) { x->data[i] = (double) rand() / RAND_MAX; } // Iterate until the x vector converges. while (1) { k++; // Multiply A * x xp1 = multiplyMatrix(a, x); // Add up all of the values in xp1 sum = 0; for (i = 0; i < a->height; i++) { sum += xp1->data[i]; } // Divide each value in xp1 by sum. (Normalize) for (i = 0; i < a->height; i++) { xp1->data[i] /= sum; } // Test to see if we need to quit. converge = 1; // Converged for (i = 0; i < a->height; i++) { if (fabs(x->data[i] - xp1->data[i]) >= EPSILON) { converge = 0; // Not converged. break; } } // Set up for the next loop. freeMatrix(x); x = copyMatrix(xp1); freeMatrix(xp1); // Really test for quit. if (converge == 1) { break; } } freeMatrix(x); return sum; }
void matrixReverse(float *matA, float *matArev, int N, int M) { float *matR, *matI, *matTmp; genIdMatrix(&matR, N); genIdMatrix(&matI, N); float coefB = 1.0f / (calcMaxColSum(matA, N) * calcMacRowSum(matA, N)); cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, N, N, N, -coefB, matA, N, matA, N, 1.0, matR, N); allocMatrix(&matTmp, N, false); int i; transposeMatrix(matR, matR, N); for (i = 0; i < M; ++i) { if (!(i & 1)) { cblas_saxpy(N * N, 1.0f, matI, 1, matArev, 1); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, N, N, N, 1.0, matI, N, matR, N, 0.0, matTmp, N); } else { cblas_saxpy(N * N, 1.0f, matTmp, 1, matArev, 1); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, N, N, N, 1.0, matTmp, N, matR, N, 0.0, matI, N); } } cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, N, N, N, coefB, matArev, N, matA, N, 0.0, matTmp, N); copyMatrix(matArev, matTmp, N); freeMatrix(matR, N); freeMatrix(matI, N); }
/*=========================================================================== * eigenvector * This algorithm determines the eigenvector of a matrix given an eigenvalue. *=========================================================================*/ matrix* eigenvector(matrix* a, double eigenvalue) { matrix* b; // This matrix will store A-eI matrix* zero; // This matrix will store a column vector of zeros matrix* out; double* ptr; int i; assert(a->width == a->height, "Matrix must be square."); // Create our column vector of zeros zero = makeMatrix(1, a->height); // Copy A b = copyMatrix(a); // Subtract eigenvalue from the diagonal elements ptr = b->data; for (i = 0; i < b->height; i++) { *ptr -= eigenvalue; ptr += b->width + 1; } // Find the eigenvector out = solver(b, zero); freeMatrix(b); freeMatrix(zero); return out; }
void pushMatrix(float * m) { if(glMatrixStackTop < MAX_MATRICES) { copyMatrix(glMatrixStack[glMatrixStackTop], m); glMatrixStackTop++; } }
void blocksCopy(double *a, int i, int j, double *b, int k, int m, int n, int r){ //a_{ij}=b; int x, y, size; x = (i<k)? m:r; y = (j<k)? m:r; size = x*y; copyMatrix(b, a + i*m*n + j*m*x, size); }
void Sbs2SourceReconstructionSparse::fista_method_group_lasso_v2(DTU::DtuArray2D<double> *A_normalized, DTU::DtuArray2D<double> *Y, double lambda, double L, DTU::DtuArray2D<double> *estimated_S) { (*S_ant)=0; double t_ant = 1; int flag = 1; double iteration_counter = 0; double f_obj_ant; f_objective_general_group_lasso(A_normalized, S_ant, Y, lambda, &f_obj_ant); (*V) = 0; double regularizer_factor = lambda / double(L); double t_act; double f_obj_act; double error_rel; // Y->print(); while(flag==1) { derivative_square_loss_frobenius(A_normalized,Y,V,grad_f_y); grad_f_y->multiply( ( 1.0 )/(double)L , one_over_L_grad_f_y); V->subtract( one_over_L_grad_f_y , V_minus_one_over_L_grad_f_y); proximal_operator_standard_group_lasso(V_minus_one_over_L_grad_f_y , ®ularizer_factor , S_act); t_act = ( 1.0 + sqrt( 1.0 + 4.0*pow(t_ant,2) ) ) / 2.0; S_act->subtract(S_ant,S_act_minus_S_ant); S_act_minus_S_ant->multiply( ( (t_ant-1.0)/t_act ) , scaled_S_act_minus_S_ant); S_act->add(scaled_S_act_minus_S_ant,V); f_objective_general_group_lasso(A_normalized,S_act,Y,lambda,&f_obj_act); error_rel = abs(f_obj_act - f_obj_ant); //qDebug() << error_rel << f_obj_act << f_obj_ant << L << lambda; if(error_rel <= error_tol) { flag=0; } t_ant = t_act; copyMatrix(S_act,S_ant); f_obj_ant = f_obj_act; ++iteration_counter; } copyMatrix(S_act,estimated_S); }
void KinematicMotion::checkRotationCorrectness() const { double M[9]; double M_inv[9]; copyMatrix(rotationMatrix, M); copyMatrix(rotationMatrix, M_inv); matrixTanspose(M_inv); matrixProduct(M_inv, M); // M = M_inv * M const double TOL = 1E-10; //printMatrix(M); assert(fabs(M[0 * 3 + 0] - 1.0) < TOL); assert(fabs(M[0 * 3 + 1] - 0.0) < TOL); assert(fabs(M[0 * 3 + 2] - 0.0) < TOL); assert(fabs(M[1 * 3 + 0] - 0.0) < TOL); assert(fabs(M[1 * 3 + 1] - 1.0) < TOL); assert(fabs(M[1 * 3 + 2] - 0.0) < TOL); assert(fabs(M[2 * 3 + 0] - 0.0) < TOL); assert(fabs(M[2 * 3 + 1] - 0.0) < TOL); assert(fabs(M[2 * 3 + 2] - 1.0) < TOL); }
void multiple_all_matrix(GLfloat M[][4]){ for(int i = 0; i < current_obj; ++i){ GLfloat I[4][4] = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; multiMatrix(I, geoMatrix[i], I); multiMatrix(I, viewMatrix, I); multiMatrix(I, projMatrix, I); copyMatrix(aMVP[i], I); transMatrix(aMVP[i]); } }
matrix_t* getGamma(const mxArray* array, size_t L) { if (mxGetN(array) != L || mxGetM(array) != L) { mexErrMsgTxt("Invalid dimension of gamma matrix."); } matrix_t* gamma = alloc_matrix(L, L); copyMatrix(gamma, array); return gamma; }
void TurnAlways::simulateUntil(unsigned long t) { unsigned long dt = t - lastV; // how long since last update float secs = ((float) dt) / 1000; // convert ms to sec lastV = t; Matrix delta, newT; rotMatrix(delta,'Y',secs * vel); multMatrix(delta,owner->transform,newT); copyMatrix(newT,owner->transform); lastV = t; }
KinematicMotion *KinematicMotion::newInverse() { // x2 = R*x1 + T ==> x1 = R^{-1} * (x2-T) = R^{-1}*x2 - R^{-1}*T double rotationMatrixInverse[9]; copyMatrix(rotationMatrix, rotationMatrixInverse); matrixTanspose(rotationMatrixInverse); double translationVectorInverse[3]; copyVector(translationVector, translationVectorInverse); vectorInverse(translationVectorInverse); KinematicMotion *t_inverse = new KinematicMotion(); t_inverse->addTranslation(translationVectorInverse); // step 1 t_inverse->addRotation(rotationMatrixInverse); // step 2, order cannot be changed return t_inverse; }
void inverse( double** a, int nRows, int nCols) { int i,j,k; double* w = new double[nCols]; double** v = allocate2DDouble( nRows, nCols); double** temp = allocate2DDouble( nRows, nCols ); for( i=0; i<nRows; i++) memset( v[i], 0, sizeof(double) * nCols ); memset( w, 0, sizeof(double) * nCols ); // SVD copyMatrix( a, temp, nRows, nCols); svdcmp(temp, nRows, nCols, w, v); for( i=0; i<nCols; i++) { if( !nearzero( w[i] ) ) w[i] = 1.0 / w[i]; } for( i=0; i<nCols; i++) for( j=0; j<nRows; j++) { temp[j][i] = temp[j][i] * w[i]; } for( i=0; i<nRows; i++) memset( a[i], 0, sizeof(double) * nCols ); for( i=0; i<nRows; i++) for( j=0; j<nCols; j++) for( k=0; k<nCols; k++) { a[i][j] += temp[i][k] * v[j][k]; // coz' v is not transposed } SAFEDELARR( w ); if( v != NULL ) { for( i=0; i<nRows; i++ ) SAFEDELARR( v[i] ); SAFEDELARR( v ); } if( temp != NULL ) { for( i=0; i<nRows; i++ ) SAFEDELARR( temp[i] ); SAFEDELARR( temp ); } }
void multiMatrix(GLfloat *A, GLfloat B[][4], GLfloat C[][4]){ GLfloat ans[4][4] = {0}; int n = 4; //print_aMVP(); transMatrix(A); for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) for(int k = 0; k < n; ++k) ans[i][j] += (B[i][k] * C[k][j]); copyMatrix(A, ans); transMatrix(A); //print_aMVP(); }
void multiMatrix(GLfloat A[][4], GLfloat *B){ GLfloat ans[4][4] = {0}; int n = 4; //print_aMVP(); transMatrix(B); for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) for(int k = 0; k < n; ++k) ans[i][j] += (A[i][k] * B[k*n+j]); copyMatrix(B, ans); transMatrix(B); //print_aMVP(); }
double computeIntersectionRoundness(vector<Matrix3x4d> const& projections, vector<PointMeasurement> const& measurements, double sigma) { Matrix3x3d const cov_X = computeIntersectionCovariance(projections, measurements, sigma); Matrix<double> sigma_X(3, 3); copyMatrix(cov_X, sigma_X); SVD<double> svd(sigma_X); Vector<double> S; svd.getSingularValues(S); return sqrt(S[2] / S[0]); }
//----------------------------------------------------------------------- void Kriging1D::cholesky(double ** K, double ** C, int md) { static const double choleskyRepairFactor = 1.001; int count = 0; while ( lib_matrCholR(md, copyMatrix(K, C, md)) ) { for (int i = 0 ; i < md ; i++) K[i][i] *= choleskyRepairFactor; count++; if (count > 5) LogKit::LogFormatted(LogKit::Low,"\nERROR in Kriging1D::Cholesky(): Could not find cholesky factor\n"); } }
void rotate(GLfloat x, GLfloat y, GLfloat z){ transport(-x_center[now], -y_center[now], -z_center[now], NO_UPDATE); GLfloat M[3][4][4] = {0}; for(int i = 0; i < 3; ++i) for(int j = 0; j < 4; ++j) M[i][j][j] = 1; const double PI = std::atan(1.0); const double ANGLE_X = PI * x / 180.0; const double ANGLE_Y = PI * y / 180.0; const double ANGLE_Z = PI * z / 180.0; const GLfloat COS[] = { std::cos(ANGLE_X), std::cos(ANGLE_Y), std::cos(ANGLE_Z) }; const GLfloat SIN[] = { std::sin(ANGLE_X), std::sin(ANGLE_Y), std::sin(ANGLE_Z) }; for(int i = 0; i < 3; ++i){ if (i == 0){ M[i][1][1] = M[i][2][2] = COS[i]; M[i][1][2] = -SIN[i]; M[i][2][1] = SIN[i]; } else if (i == 1){ M[i][0][0] = M[i][2][2] = COS[i]; M[i][0][2] = -SIN[i]; M[i][2][0] = SIN[i]; } else { M[i][0][0] = M[i][1][1] = COS[i]; M[i][0][1] = -SIN[i]; M[i][1][0] = SIN[i]; } GLfloat I[4][4] = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; multiMatrix(geoMatrix[now], M[i], geoMatrix[now]); multiple_all_matrix(M[i]); copyMatrix(aMVP[now], I); } transport(x_center[now], y_center[now], z_center[now], NO_UPDATE); }
int main() { matrix m, orig; matrix eigen_vectors; int size, c; printf("Enter matrix from: (1) file, (2) keyboard, (3) gilbert? "); scanf("%d", &c); switch (c) { case 1: inputFileMatrix(m, &size); break; case 2: keybordMatrix(m, &size); break; case 3: hilbertMatrix(m, &size); break; default: return 0; } printf("Output: (1) file, (2) display? "); scanf("%d", &c); if (c == 1) { FILE * output; output = fopen("output.txt","w"); stdout = output; } printf("\nInput matrix"); printMatrix(m, size); copyMatrix(orig, m, size); setIdentityMatrix(eigen_vectors, size); int iterations = roundRobin(m, eigen_vectors, size); printf("\n------------------------------------"); printf("\nAmount iterations: %d\n", iterations); printf("\nEigenvalues:\n"); printDiagonal(m, size); printf("\nEigenvectors:"); printMatrix(eigen_vectors, size); if (c != 1) analysisOfResults(m, orig, eigen_vectors, size); return 0; }