Exemplo n.º 1
0
double do_work(void) {
  double **a,           /* matrix A to be multiplied */
         **b,           /* matrix B to be multiplied */
         **c;           /* result matrix C */
  a = allocateMatrix(NRA, NCA);
  b = allocateMatrix(NCA, NCB);
  c = allocateMatrix(NRA, NCB);

  /*** Spawn a parallel region explicitly scoping all variables ***/

  initialize(a, NRA, NCA);
  initialize(b, NCA, NCB);
  initialize(c, NRA, NCB);

  compute(a, b, c, NRA, NCA, NCB);
  compute_interchange(a, b, c, NRA, NCA, NCB);

  double result = c[0][1];

  freeMatrix(a, NRA, NCA);
  freeMatrix(b, NCA, NCB);
  freeMatrix(c, NCA, NCB);

  return result;
}
Exemplo n.º 2
0
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);
}
Exemplo n.º 3
0
/* This method performs an L2 based distance measure
after solving for a best fit transformation.  The
best fit transformation is a combination of a 2D
scale, rotation and translation.  The algorithm
solves for this transformation using a least squares
solution to a set of transformation aproximations. */
FTYPE GeometrySimLeastSquaresNLS(FaceGraph f1, FaceGraph f2){
    int i;
    FTYPE dist = 0.0;

    Matrix g1 = makeMatrix(f1->geosize*2,1);
    Matrix g2 = makeMatrix(f1->geosize*2,1);

    for (i = 0; i < f1->geosize; i++) {
        FTYPE dedx=0, dedy=0;
        DENarrowingLocalSearch(f1->jets[i],f2->jets[i],&dedx,&dedy);

        ME(g1,2*i,0)   = f1->jets[i]->x ;
        ME(g1,2*i+1,0) = f1->jets[i]->y ;
        ME(g2,2*i,0)   = f2->jets[i]->x + dedx;
        ME(g2,2*i+1,0) = f2->jets[i]->y + dedy;
    }

    TransformLeastSquares(g1,g2);

    dist = L2Dist(g1, g2);

    freeMatrix(g1);
    freeMatrix(g2);

    return dist;
}
Exemplo n.º 4
0
Arquivo: main.c Projeto: skoneka/prir
int main(void)
{
    init();
    matrix_data_t m = {0};
    filesToMatrix(&m, "A.txt", "B.txt");

    /* A*B=C using thread pool */
    mulMatrix(&m);

    /* return codes of threads */

    printMatrix(&m.A);
    printf("---\n");
    printMatrix(&m.B);
    printf("---\n");
    printMatrix(&m.C);
    printf("---\n");

    /* mutex use show off */
    /* VERBOSE fprintf(stderr, "Sum C with threads\n"); */
    sumCMatrixElements(&m);
    printf("Sum = %f\n", theSum);

    freeMatrix(&m.A);
    freeMatrix(&m.B);
    freeMatrix(&m.C);
    return 0;
}
Exemplo n.º 5
0
void DOsvd(float *a,float *res,float *comp,float *values,int nframes,int framesize,int compressedsize)
{
	int *remap;
	int i,j;
	int nrows;
	nrows=nframes;
	if (nrows<framesize)
		nrows=framesize;
	double **da=allocMatrix(nrows,framesize);
	double **v=allocMatrix(framesize,framesize);
	double *w=allocVect(framesize);
	float mx;
	int bestat;

	for (j=0;j<framesize;j++)
	{
		for (i=0;i<nframes;i++)
			da[j+1][i+1]=a[i*framesize+j];
		for (;i<nrows;i++)
			da[j+1][i+1]=0.0;
	}

	svdcmp(da,nrows,framesize,w,v);

	remap=new int[framesize];


	for (i=0;i<framesize;i++)
		remap[i]=-1;
	for (j=0;j<compressedsize;j++)
	{
		mx=-1.0f;
		for (i=0;i<framesize;i++)
		{
			if (remap[i]<0&&fabs(w[i+1])>mx)
			{
				mx=fabs(w[i+1]);
				bestat=i;
			}
		}
		assert(mx>-.5f);
		remap[bestat]=j;
	}
	// josh **DO NOT** put your dof>nframes mod here
	for (i=0;i<framesize;i++)
	{
		if (remap[i]<0)
			w[i+1]=0.0;
		else
		{
			values[remap[i]]=w[i+1];
			for (j=0;j<framesize;j++)
				res[remap[i]*framesize+j]=v[j+1][i+1];
		}
	}
	freeVect(w);
	freeMatrix(v,framesize);
	freeMatrix(da,nrows);
	delete[] remap;
}
Exemplo n.º 6
0
 double capacitor(double a, double b, double c, double d, int n, double tol, double rel){
    double h=0.5*c/n; // Grid size.

    int na=round(0.5*a/h);
    // double x=linspace(0, 0.5*c, n+1);
    int m=round(0.5*d/h);
    int mb=round(0.5*b/h);
    // double y=linspace(0, 0.5*d, m+1);

    // Initialize potential and mask array.
    double** f = createMatrix(n+1, m+1, 0);
    double** mask = createMatrix(n+1, m+1, rel);

    for(int ii=0;ii<=na;ii++){
        for(int jj=0;jj<=mb;jj++){
            mask[ii][jj] = 0;
            f[ii][jj] = 1;
        }
    }
    double oldcap = 0, cap = 0;
    for(int iter=0;iter < 1000; iter++){
        seidel(f, mask, n, m, na, mb); 
        cap = gauss(n, m, h, f);
        if(fabs(cap-oldcap)/cap < tol)
            break;
        else
            oldcap = cap;
    }
    freeMatrix(f);
    freeMatrix(mask);
    return cap;
 }
Exemplo n.º 7
0
void myMxM(Matrix A, Matrix v, Matrix u)
{
  Matrix temp = createMatrix(A->rows, v->cols);
#pragma omp parallel
  {
    int* displ, *cols;
    splitVector(v->cols, num_threads(), &cols, &displ);
    MxM2(A, v, temp, displ[get_thread()], cols[get_thread()],
         displ[get_thread()], 1.0, 0.0);
    free(cols);
    free(displ);
  }
#ifdef HAVE_MPI
  for (int i=0;i<v->as_vec->comm_size;++i) {
    Matrix t = subMatrix(temp, v->as_vec->displ[i]/v->cols,
                         v->as_vec->sizes[i]/v->cols, 0, v->cols);
    MPI_Reduce(t->data[0], u->data[0], v->as_vec->sizes[i],
               MPI_DOUBLE, MPI_SUM, i, *v->as_vec->comm);
    freeMatrix(t);
  }
#else
  memcpy(u->data[0], temp->data[0], u->as_vec->len*sizeof(double));
#endif
  freeMatrix(temp);
}
Exemplo n.º 8
0
int main(int argc, char** argv)
{
  if (argc < 3) {
    printf("need two parameters, the matrix size and the number of vectors\n");
    return 1;
  }
  int N=atoi(argv[1]);
  int K=atoi(argv[2]);

  Matrix A = createMatrix(N,N);
  // identity matrix
  for (int i=0;i<N;++i)
    A->data[i][i] = 1.0;

  Matrix v = createMatrix(N,K);

  // fill with column number
  for (int i=0;i<K;++i)
    for (int j=0;j<N;++j)
      v->data[i][j] = i;

  Matrix v2 = createMatrix(N,K);
  double time = WallTime();
  MxM(A, v, v2, 1.0, 0.0);
  double sum = innerproduct(v->as_vec, v2->as_vec);

  printf("sum: %f\n", sum);
  printf("elapsed: %f\n", WallTime()-time);
  freeMatrix(v2);
  freeMatrix(v);
  freeMatrix(A);
  return 0;
}
Exemplo n.º 9
0
Arquivo: main.c Projeto: fevrite/lmp9
int main(int argc, char ** argv) {
	int res;
	Matrix * A = readFromFile(argv[1]);
	Matrix * b = readFromFile(argv[2]);
	Matrix * x;

	if (A == NULL) return -1;
	if (b == NULL) return -2;
	printToScreen(A);
	printToScreen(b);

	res = eliminate(A,b);
	x = createMatrix(b->r, 1);
	if (x != NULL) {
		res = backsubst(x,A,b);

		printToScreen(x);
	  freeMatrix(x);
	} else {
					fprintf(stderr,"Błąd! Nie mogłem utworzyć wektora wynikowego x.\n");
	}

	freeMatrix(A);
	freeMatrix(b);

	return 0;
}
Exemplo n.º 10
0
void freeImage(image * img)
{
    freeMatrix(img->red);
    freeMatrix(img->green);
    freeMatrix(img->blue);
    free(img);
}
Exemplo n.º 11
0
int main(int argc, char** argv)
{
  int N, K, i, j;
  Matrix A,v;
  double time, sum;

  if (argc < 3) {
    printf("need two parameters, the matrix size and the number of vectors\n");
    return 1;
  }

  N=atoi(argv[1]);
  K=atoi(argv[2]);

  A = createMatrix(N,N);
  // identity matrix
  for (i=0;i<N;++i)
    A->data[i][i] = 1.0;

  v = createMatrix(N,K);
  // fill with column number
  for (i=0;i<K;++i)
    for (j=0;j<N;++j)
      v->data[i][j] = i;

  time = WallTime();
  sum = dosum(A,v);
  printf("sum: %f\n", sum);
  printf("elapsed: %f\n", WallTime()-time);
  freeMatrix(v);
  freeMatrix(A);

  return 0;
}
Exemplo n.º 12
0
void cg(eval_t A, Matrix b, double tolerance, void* ctx)
{
  Matrix r = createMatrix(b->rows, b->cols);
  Matrix p = createMatrix(b->rows, b->cols);
  Matrix buffer = createMatrix(b->rows, b->cols);
  double dotp = 1000;
  double rdr = dotp;
  copyVector(r->as_vec,b->as_vec);
  fillVector(b->as_vec, 0.0);
  int i=0;
  while (i < b->as_vec->len && rdr > tolerance) {
    ++i;
    if (i == 1) {
      copyVector(p->as_vec,r->as_vec);
      dotp = innerproduct(r->as_vec,r->as_vec);
    } else {
      double dotp2 = innerproduct(r->as_vec,r->as_vec);
      double beta = dotp2/dotp;
      dotp = dotp2;
      scaleVector(p->as_vec,beta);
      axpy(p->as_vec,r->as_vec,1.0);
    }
    A(buffer,p,ctx);
    double alpha = dotp/innerproduct(p->as_vec,buffer->as_vec);
    axpy(b->as_vec,p->as_vec,alpha);
    axpy(r->as_vec,buffer->as_vec,-alpha);
    rdr = sqrt(innerproduct(r->as_vec,r->as_vec));
  }
  printf("%i iterations\n",i);
  freeMatrix(r);
  freeMatrix(p);
  freeMatrix(buffer);
}
Exemplo n.º 13
0
/*===========================================================================
 * 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;
}
Exemplo n.º 14
0
/*===========================================================================
 * 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;
}
Exemplo n.º 15
0
void matrixSquareRoot(Matrix* A, Matrix* S)
{
  //Approach is to do an SVD of A, then set S to V * sqrt(Sigma) * Vtransposed
  int i, j;

  Matrix* U = allocateMatrix(A->rows, A->columns);
  Matrix* Vtransposed = allocateMatrix(A->rows, A->columns);
  Matrix* Sigma = allocateMatrix(A->rows, A->columns);

  //First do an SVD
  singularValueDecomposition(A, U, Vtransposed, Sigma);

  //Now calculate sqrt(Sigma) * Vtransposed and stick it in U
  for(i = 0; i < Sigma->rows; i++)
  {
    for(j = 0; j < Sigma->columns; j++)
    {
      U->pointer[i + j * U->rows] = Vtransposed->pointer[i + j * Vtransposed->rows] * sqrt(Sigma->pointer[i + i * Sigma->rows]);
    }
  }

  multiplyMatrices(Vtransposed, U, S, 1, 0);

  freeMatrix(U);
  freeMatrix(Vtransposed);
  freeMatrix(Sigma);
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{

	if(argc < 2) {
		printf("Usage: matrix-thread nThreads\n");
		return -1;
	}
	numThreads = atoi(argv[1]);
	A = readMatrix(IN_1);
	B = readMatrix(IN_2);
	if(A->numCols != B->numRows) {
		fprintf(stderr, "Wrong matrix dimensions\n");
		return -1;
	}
	C = makeMatrix(A->numRows, B->numCols);

	dispatchThreads();

	writeMatrix(OUTPUT_FILE, C);

	freeMatrix(A);
	freeMatrix(B);
	freeMatrix(C);
	return 0;
}
Exemplo n.º 17
0
Arquivo: kurucz.c Projeto: kouui/rh
void free_BS(Barklemstruct *bs)
{
  free(bs->neff1);
  free(bs->neff2);

  freeMatrix((void **) bs->cross);
  freeMatrix((void **) bs->alpha);
}
Exemplo n.º 18
0
Matrix
build_A(int m){
    Matrix K = build_K(2*m);
    Matrix L = build_L(2*m);
    Matrix A = matrixMult(K, L);
    freeMatrix(K);
    freeMatrix(L);
    return A;
}
Exemplo n.º 19
0
/**
eigentrain

computes the eigen space for matrix images.

This function is used in the training procedure of the face recognition pca
algorithm.
INPUT:  the data matrix of images
OUTPUT: mean: the mean value of the images
eigen_values: eigenvalues
eigen_base: eigenvectors

The data matrix is mean centered, and this is a side effect.
*/
void eigentrain(Matrix *mean, Matrix *eigen_vals,
                Matrix *eigen_base, Matrix images) 
{
    double p = 0.0;
    Matrix M, eigenvectors;

    DEBUG(1, "Calculating mean image.");
    *mean = get_mean_image(images);

    DEBUG(1, "Calculating the mean centered images for the training set.");
    mean_subtract_images(images, *mean);

    MESSAGE2ARG("Calculating Covariance Matrix: M = images' * images. M is a %d by %d Matrix.", images->col_dim, images->col_dim);
    M = transposeMultiplyMatrixL(images, images);
    DEBUG_INT(3, "Covariance Matrix Rows", M->row_dim);
    DEBUG_INT(3, "Covariance Matrix Cols", M->col_dim);

    DEBUG(2, "Allocating memory for eigenvectors and eigenvalues.");
    eigenvectors = makeMatrix(M->row_dim, M->col_dim);
    *eigen_vals = makeMatrix(M->row_dim, 1);


    MESSAGE("Computing snap shot eigen vectors using the double precision cv eigensolver.");

    cvJacobiEigens_64d(M->data, eigenvectors->data, (*eigen_vals)->data, images->col_dim, p, 1);

    freeMatrix(M);

    DEBUG(1, "Verifying the eigen vectors");
    /* Reconstruct M because it is destroyed in cvJacobiEigens */
    M = transposeMultiplyMatrixL(images, images);
    if (debuglevel >= 3)
        eigen_verify(M, *eigen_vals, eigenvectors);
    freeMatrix(M);

    *eigen_base = multiplyMatrix(images, eigenvectors);
    MESSAGE2ARG("Recovered the %d by %d high resolution eigen basis.", (*eigen_base)->row_dim, (*eigen_base)->col_dim);

    DEBUG(1, "Normalizing eigen basis");
    basis_normalize(*eigen_base);

    /*Remove last elements because they are unneeded.  Mean centering the image
    guarantees that the data points define a hyperplane that passes through
    the origin. Therefore all points are in a k - 1 dimensional subspace.
    */
    (*eigen_base)->col_dim -= 1;
    (*eigen_vals)->row_dim -= 1;
    eigenvectors->col_dim -= 1;

    DEBUG(1, "Verifying eigenbasis");
    if (debuglevel >= 3)
        basis_verify(images, *eigen_base);

    /* The eigenvectors for the smaller covariance (snap shot) are not needed */
    freeMatrix(eigenvectors);
}
Exemplo n.º 20
0
Arquivo: me.c Projeto: rforge/phyloc
void me_o(double *X, int *N, char **labels, char **treeStr, int *nni)
{
  double **D, **A;
  set *species, *slooper;
  node *addNode;
  tree *T;
  char *str;
  int n, nniCount;

  n = *N;
  T = NULL;
  nniCount = 0;
  species = (set *) malloc(sizeof(set));
  species->firstNode = NULL;
  species->secondNode = NULL;
  str = (char *)R_alloc(MAX_INPUT_SIZE, sizeof(char));
  /* added by EP */
  if (strlen(str))
    strncpy(str, "", strlen(str));
  /* end */

  D = loadMatrix (X, labels, n, species);
  A = initDoubleMatrix(2 * n - 2);

  for(slooper = species; NULL != slooper; slooper = slooper->secondNode)
  {
    addNode = copyNode(slooper->firstNode);
    T = GMEaddSpecies(T,addNode,D,A);
  }
  makeOLSAveragesTable(T,D,A);
  // Compute NNI
  if (*nni == 1)
    NNI(T,A,&nniCount,D,n);
  assignOLSWeights(T,A);

  NewickPrintTreeStr(T,str);

  if (strlen (str) < MAX_INPUT_SIZE -1)
    {
      *treeStr = (char *)R_alloc(MAX_INPUT_SIZE, sizeof(char));
      /* added by EP */
      if (strlen(*treeStr))
	strncpy(*treeStr, "", strlen(*treeStr));
      /* end */
      strncpy (*treeStr, str, strlen (str));
    }

 /*  free (str); */
  freeMatrix(D,n);
  freeMatrix(A,2*n - 2);
  freeSet(species);
  freeTree(T);
  T = NULL;

  return;
}
Exemplo n.º 21
0
void
gaussianEstimator_Pred ( Matrix *xEst, Matrix *CEst, Matrix *U, Matrix *Cw, Matrix (*afun)(Matrix m, float t), float *dt, Matrix *m_opt)
{
float D = elem(sizeOfMatrix(*m_opt),0,1)+1;       //printf("%f\n", D);
float w_opt = 1/D;                                //printf("%f\n", w_opt);
float Nx = elem(sizeOfMatrix(*xEst),0,0);         //printf("%f\n", Nx);
float d = Nx*(D-1) + 1;                           //printf("%f\n", d);
float w = 1/d;                                    //printf("%f\n", w);

/* Eigenvectors, Eigenvalues */
int dimC = elem ( sizeOfMatrix(*CEst), 0, 0 );
Matrix Vec = zeroMatrix(dimC, dimC);    
Matrix Val = zeroMatrix(dimC, dimC);
eig ( CEst, &Vec, &Val );

/* m1 = vec*sqrtf(val) */
int i;
for ( i = 0; i < dimC; ++i )
    setElem(Val, i, i, sqrtf(fabs(elem(Val, i,i))));
Matrix m1 = mulMatrix(Vec, Val);

freeMatrix(Vec);
freeMatrix(Val);

/*  rotate & scale samples: m = m1*S */
Matrix m = scaledSamplePoints(m1, *m_opt);

/* x = x*ones(1,d) */
Matrix x = fillMatrix(*xEst, d);

/* shift samples: m = m + x */
m = addMatrix(m, x);              //printMatrix(m);

/* afun */
/* Prediction: mean
   xPredDiracs = feval(afun,m, [], [], t);
   xPred = w*sum(xPredDiracs, 2);*/
   
Matrix xPredDiracs = (*afun) (m, *dt);                   //printMatrix(xPredDiracs);
Matrix xPredDiracsSum = sumMatrix(xPredDiracs, 2);       //printMatrix(xPredDiracsSum);
Matrix xPred = mulScalarMatrix(w, xPredDiracsSum);       //printMatrix(xPred);

//mxDiracs = xPredDiracs-repmat(xPred, 1, d);
//CPred = w_opt*mxDiracs*mxDiracs';
Matrix mxDiracs = subMatrix(xPredDiracs, fillMatrix(xPred, d));   //printMatrix(mxDiracs);
Matrix CPred = mulScalarMatrix(w_opt, mulMatrix(mxDiracs, transposeMatrix(mxDiracs)));  //printMatrix(CPred);


//RETURN
*xEst = xPred;        //printMatrix(*xEst);
*CEst = CPred;        //printMatrix(*CEst);

freeMatrix(m);
freeMatrix(xPredDiracs);
freeMatrix(xPredDiracsSum);
}
Exemplo n.º 22
0
/* HMM deconstructor */
HMM::~HMM()
{

	//delete[] initial_probability;
	freeMatrix(_pTransition, _maxState, _numStates);
	freeMatrix(_pObservation, _numStates, _numObs);
	delete[] _pState;
	freeMatrix(condstate_dist, _numObs, _numStates);

}
Exemplo n.º 23
0
Arquivo: main.c Projeto: etoestja/inf
int main(int argc, char** argv)
{
/*    printf("argc=%d\n", argc);
    int ss;
    for(ss = 0; ss < argc; ss++)
        printf("argv#%d=%s\n", ss, argv[ss]);
*/

    int N;
    scanf("%d", &N);
    matrix *M1 = malloc(sizeof(matrix)), *M2 = malloc(sizeof(matrix));
    mallocMatrix(M1, N, N);
    mallocMatrix(M2, N, N);

    fillMatrix(M1);

    #ifdef DEBUG
        fprintf(stderr, "A=\n");
        printMatrix(M1);
    #endif

    getInverseCopy(M1, M2, NULL);

    #ifdef DEBUG
        fprintf(stderr, "A^-1=\n");
        printMatrix(M2);
    #else
        if(argc == 1 || (argc >= 2 && argv[1][0] == 'i'))
        {
            printf("%d\n", M2->R);
            printMatrix(M2);
        }
    #endif

    matrix *M3 = malloc(sizeof(matrix));
    mallocMul(M1, M2, M3);
    mulMatrix(M1, M2, M3);

    #ifdef DEBUG
        fprintf(stderr, "A*A^-1=\n");
        printMatrix(M3);
    #else
        if(argc >= 2 && argv[1][0] == 'e')
        {
            printf("%d\n", M3->R);
            printMatrix(M3);
        }
    #endif

    freeMatrix(M1);
    freeMatrix(M2);

    return(0);
}
Exemplo n.º 24
0
void matrix(int taintcount) {
    x = allocMatrix(dimension, TAINT_CAMERA, taintcount);
    y = allocMatrix(dimension, 0, 0);
    o = allocMatrix(dimension, 0, 0);

    int i, j;
    /* init matrix */
    for (i = 0; i < dimension; i++){
        for(j = 0; j < dimension; j++){
            x[i][j] = i + j;
            y[i][j] = i + j;
            o[i][j] = 0;
        }
    }

    // double start, end, delta;
    struct timespec start, end;

    if (emu) {
        // emu_set_protect(true);
        emu_mprotect_mem(true);
        emu_reset_stats();
        time_ns(&start);
        EMU_MARKER_START;
    } else {
        time_ns(&start);
    }

    for (i = 0; i < runs; i++) {
    // M(matrixLoop());
        matrixLoop();
    }

    if (emu) {
        EMU_MARKER_STOP;
        time_ns(&end);
        emu_unprotect_mem();
        emu_dump_stats();
        /* emu_dump_taintmaps(); */
        emu_dump_taintpages();
    } else {
        time_ns(&end);
    }

    printf("cycles = %lld\n", ns_to_cycles(diff_ns(&start, &end)) / runs);

    /* free matrix */
    /* dealloc(x, dimension); */
    /* dealloc(y, dimension); */
    /* dealloc(o, dimension); */
    freeMatrix(x, dimension);
    freeMatrix(y, dimension);
    freeMatrix(o, dimension);
}
Exemplo n.º 25
0
void KalmanFilter::getPPlus() {
  double** prod1 = productMatrix(A,P,3,3,3);
  double** tA = transposeMatrix(A,3,3);
  double** prod2 = productMatrix(prod1,tA,3,3,3);

  freeMatrix(P,3);
  P = addMatrix(prod2,Q,3,3);

  freeMatrix(prod1,3);
  freeMatrix(prod2,3);
  freeMatrix(tA,3);
}
Exemplo n.º 26
0
Arquivo: mxm.c Projeto: akva2/tma4280
int main(int argc, char **argv )
{
  int size, rank;
  long i, j, l, m, n, k, iter, loop;
  Matrix a, b, c;
  double t1, t2, dt, dt1, r;

  init_app(argc, argv, &rank, &size);

  if( argc < 3 ) {
    if (rank == 0)
      printf("need atleast 2 arguments - n & flag\n");
    close_app();
    return 1;
  }

  k = m = n = atoi(argv[1]);
  a = createMatrix(m, k);
  b = createMatrix(k, n);
  c = createMatrix(m, n);

  for (i=0; i  < m; i++) {
    for (l=0; l < k; l++) {
      a->data[l][i] = i+1.0;
    }
  }
  for (l=0; l  < k; l++) {
    for (j=0; j < n; j++) {
      b->data[j][l] = j+1.0;
    }
  }
  loop = 5;

  t1 = WallTime(); 
  for (iter=0; iter < loop; iter++)
    mxm (a,b,c,atoi(argv[2]));
  t2 = WallTime();

  dt = t2 - t1;
  dt1 = dt/(m*2*k*n);
  dt1 = dt1/loop;
  r    = 1.e-6/dt1;
  printf (" matrix-matrix : (m,k,n)= (%ld,%ld,%ld)    dt= %lf (s) dt1= %le r= %lf\n" ,m, k, n, dt, dt1, r);

  freeMatrix(a);
  freeMatrix(b);
  freeMatrix(c);

  close_app();

  return 0;
}
Exemplo n.º 27
0
void KalmanFilter::getP(double** K) {
  double** tmp = productMatrix(K,H,3,3,2);
  double** subI = substractionIdMatrix(tmp,3);

  freeMatrix(tmp,3);

  tmp = productMatrix(subI,P,3,3,3);

  freeMatrix(P,3);
  freeMatrix(subI,3);

  P = tmp;
}
Exemplo n.º 28
0
int main(int argc, char** argv)
{
  int rank, size;
  init_app(argc, argv, &rank, &size);

  if (argc < 3) {
    printf("need two parameters, the matrix size and the number of vectors\n");
    close_app();
    return 1;
  }
  int N=atoi(argv[1]);
  int K=atoi(argv[2]);

  Matrix A = createMatrix(N,N);
  // identity matrix
  for (int i=0;i<N;++i)
    A->data[i][i] = 1.0;
  
  int *displ, *cols;
  splitVector(K, size, &cols, &displ);
  Matrix v = createMatrix(N,cols[rank]);
  // fill with column number
  for (int i=0;i<cols[rank];++i)
    for (int j=0;j<N;++j)
      v->data[i][j] = i+displ[rank];

  double time = WallTime();
  double sum = dosum(A,v);

  if (rank == 0) {
    printf("sum: %f\n", sum);
    printf("elapsed: %f\n", WallTime()-time);
  }

  char s[128];
  sprintf(s,"vec-%i.asc", rank);
  saveVectorSerial(s, v->as_vec);
  sprintf(s,"mat-%i.asc", rank);
  saveMatrixSerial(s, v);

  sprintf(s,"vec.asc");
  saveVectorMPI(s, v->as_vec);

  freeMatrix(v);
  freeMatrix(A);
  free(displ);
  free(cols);

  close_app();
  return 0;
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
{
	struct matrix *m, *n, *result;

	/* create structure and fill array */
	m = createMatrix(3, 2);

	m->A[0][0] = 1;
	m->A[0][1] = 2;
	m->A[1][0] = 3;
	m->A[1][1] = 4;
	m->A[2][0] = 5;
	m->A[2][1] = 6;

	printf("First Matrix\n");
	printMatrix(m);

	/* create a second structure and fill array */
	n = createMatrix(3, 2);

	n->A[0][0] = 6;
	n->A[0][1] = 5;
	n->A[1][0] = 4;
	n->A[1][1] = 3;
	n->A[2][0] = 2;
	n->A[2][1] = 1;

	printf("Second Matrix\n");
	printMatrix(n);

	/* call add function and print results */
	result = add(m, n);

	printf("Add result\n");
	printMatrix(result);

	freeMatrix(result);

	/* call multiply function and print results */
	result = multiply(m, n);

	printf("Multiply result\n");
	printMatrix(result);

	freeMatrix(result);

	freeMatrix(m);
	freeMatrix(n);

	return 0;
}
Exemplo n.º 30
0
int main(int argc, char* argv[]){
	int tam=0;
	struct timeval t_ini, t_fin;
	num **A=NULL, **B=NULL, **e_matrix=NULL, **t_matrix=NULL, **B_t=NULL;
	int i=0, j=0;
	tam=atoi(argv[1]);
	
	/*Generar las matrices*/
	A=generateMatrix(tam);
	B=generateMatrix(tam);
	e_matrix=generateEmptyMatrix(tam);
	t_matrix=generateEmptyMatrix(tam);
	B_t=generateEmptyMatrix(tam);
	
	/*Multiplicar matrices*/
		/* Multiplicacion normal*/
	gettimeofday(&t_ini,NULL);
	mult(A, B, e_matrix,tam);
	gettimeofday(&t_fin,NULL);
	printf("%f\n", ((t_fin.tv_sec*1000000+t_fin.tv_usec)-(t_ini.tv_sec*1000000+t_ini.tv_usec))*1.0/1000000.0);
	
		/*Multiplicacion traspuesta*/	
	traspuesta(B, B_t, tam);
	gettimeofday(&t_ini, NULL);
	mult_t(A, B_t, t_matrix,tam);
	gettimeofday(&t_fin, NULL);
	printf("%f\n", ((t_fin.tv_sec*1000000+t_fin.tv_usec)-(t_ini.tv_sec*1000000+t_ini.tv_usec))*1.0/1000000.0);
	
	
	/*printf("Normal\n");
	for(i=0; i<tam; i++){
		for(j=0; j<tam; j++){
			printf("| %f |", B[i][j]);
		}
		printf("\n");
	}
	printf("\nTraspueta\n");
	for(i=0; i<tam; i++){
		for(j=0; j<tam; j++){
			printf("| %f |", B_t[i][j]);
		}
		printf("\n");
	}*/
	freeMatrix(A);
	freeMatrix(B);
	freeMatrix(B_t);
	freeMatrix(e_matrix);
	freeMatrix(t_matrix);
	return 0;
}