Exemplo n.º 1
0
int main()
{

	int a[3][3];
	int b[3][3];
	int c[3][3];

	//Q2: define pointers (5)
	//Define pointers ap, bp, and cp to the matrices that are defined above

	//SOLUTION CODE
	int* ap = &a[0][0];
	int* bp = &b[0][0];
	int* cp = &c[0][0];
	//SOLUTION CODE

	initialize_matrices(ap, bp, cp);

	printf("Matrix a:\n");
	fill_matrix(ap);

	printf("Matrix b:\n");
	fill_matrix(bp);

	add_matrices(ap, bp, cp);

	print_sum_matrix(cp);

	return 0;
}
Exemplo n.º 2
0
MDArray<double> Shrinkage::combine(MDArray<double> target,MDArray<double> MLE,double lambda)
{
	assert(target.get_shape() == MLE.get_shape());

	//        assert(lambda>=0 && lambda<=1);
	lambda = std::max(lambda, 0.0);
	lambda = std::min(lambda, 1.0);

	return add_matrices(mult_num_to_matrix(target,lambda),mult_num_to_matrix(MLE,1-lambda));
}
Exemplo n.º 3
0
//#define DEBUG
void SymList::compute_subgroup()
{
    Matrix2D<DOUBLE> I(4, 4);
    I.initIdentity();
    Matrix2D<DOUBLE> L1(4, 4), R1(4, 4), L2(4, 4), R2(4, 4), newL(4, 4), newR(4, 4);
    Matrix2D<int>    tried(true_symNo, true_symNo);
    int i, j;
    int new_chain_length;
    while (found_not_tried(tried, i, j, true_symNo))
    {
        tried(i, j) = 1;

        get_matrices(i, L1, R1);
        get_matrices(j, L2, R2);
        newL = L1 * L2;
        newR = R1 * R2;
        new_chain_length = __chain_length(i) + __chain_length(j);
        Matrix2D<DOUBLE> newR3 = newR;
        newR3.resize(3,3);
        if (newL.isIdentity() && newR3.isIdentity()) continue;

        // Try to find it in current ones
        bool found;
        found = false;
        for (int l = 0; l < SymsNo(); l++)
        {
        	get_matrices(l, L1, R1);
            if (newL.equal(L1) && newR.equal(R1))
            {
                found = true;
                break;
            }
        }

        if (!found)
        {
//#define DEBUG
#ifdef DEBUG
           std::cout << "Matrix size " << tried.Xdim() << " "
            << "trying " << i << " " << j << " "
            << "chain length=" << new_chain_length << std::endl;
            std::cout << "Result R Sh\n" << newR;
#endif
#undef DEBUG
            newR.setSmallValuesToZero();
            newL.setSmallValuesToZero();
            add_matrices(newL, newR, new_chain_length);
            tried.resize(MAT_YSIZE(tried) + 1, MAT_XSIZE(tried) + 1);
        }
    }
}
Exemplo n.º 4
0
static char *test_add_matrices()
{
	// We should create 2 empty matrices. If we add them we should get
	// an empty matrix.
	Matrix *a = create_matrix(2, 2);
	Matrix *b = create_matrix(2, 2);
	// We will store the result of the adition in a third matrix c.
	Matrix *c = create_matrix(2, 2);

	add_matrices(a, b, &c);

	// Since a and b are empty their result will an empty matrix too
	// so it makes sense to compare c against b or a.
	mu_assert("c != a or b", compare_matrices(a, c));


	destroy_matrix(a);
	destroy_matrix(b);
	destroy_matrix(c);
	
	return 0;
}
int main(void)
{
    int m1[100][100], m2[100][100], destination_matrix[100][100], n_rows, n_columns, i, j;     //defining all the variables
    scanf ("%d %d", &n_rows, &n_columns);      // enter the number of rows and columns for matrices
    printf("Enter the First matrix->");
      for(i=0;i<n_rows;i++)
          for(j=0;j<n_columns;j++)
               scanf("%d",&m1[i][j]);         // enter matrix m1
    printf("\nEnter the Second matrix->");
      for(i=0;i<n_rows;i++){
          for(j=0;j<n_columns;j++){
               scanf("%d",&m2[i][j]);         // enter matrix m2
          }
      }
    add_matrices(m1, m2, destination_matrix, n_rows,n_columns);      // call value from function "add_matrices"
      for(i=0;i<n_rows;i++){
          for(j=0;j<n_columns;j++){
          	  printf ("%d ",destination_matrix[i][j]);               // print/show the resulting matrix from the addition
          }
          printf ("\n");
      }
          return 0;
}
Exemplo n.º 6
0
/**
 * NAME: strassen_postprocess
 * INPUT: MATRIX* mOrig, MATRIX* mNew2, int colSize, int rowSize
 * USAGE: Strips zeros from mOrig and outputs a new rowSize by colSize matrix.
 * 
 * NOTES: Assumes all inputs are already initialized.
 */
void strassen_helper(MATRIX* m1, MATRIX* m2, MATRIX* res)
{
    // base case
    if (m1->numRows <= 1)
    {
        mult_bignums(&m1->matrix[0][0], &m2->matrix[0][0], &res->matrix[0][0]);
    }
    else
    {
        // split mOrig1 & mOrig2 into a 2x2 of submatrices
        int n = m1->numRows/2;
        

           
        // Initialize submatrices    
        MATRIX* a11 = malloc(sizeof(MATRIX));
        MATRIX* a12 = malloc(sizeof(MATRIX));
        MATRIX* a21 = malloc(sizeof(MATRIX));
        MATRIX* a22 = malloc(sizeof(MATRIX));
        MATRIX* b11 = malloc(sizeof(MATRIX));
        MATRIX* b12 = malloc(sizeof(MATRIX));
        MATRIX* b21 = malloc(sizeof(MATRIX));
        MATRIX* b22 = malloc(sizeof(MATRIX));
        zero_matrix(n,n,a11);
        zero_matrix(n,n,a12);
        zero_matrix(n,n,a21);
        zero_matrix(n,n,a22);
        zero_matrix(n,n,b11);
        zero_matrix(n,n,b12);
        zero_matrix(n,n,b21);
        zero_matrix(n,n,b22);
        
        // Strassens algorithm
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                // First matrix
                a11->matrix[i][j] = m1->matrix[i][j];          
                a12->matrix[i][j] = m1->matrix[i][j+n];   
                a21->matrix[i][j] = m1->matrix[i+n][j];    
                a22->matrix[i][j] = m1->matrix[i+n][j+n];
             
                // Second matrix
                b11->matrix[i][j] = m2->matrix[i][j];            
                b12->matrix[i][j] = m2->matrix[i][j+n];    
                b21->matrix[i][j] = m2->matrix[i+n][j];    
                b22->matrix[i][j] = m2->matrix[i+n][j+n]; 
            }
        }

        // Create two temporary matrices
        MATRIX* temp1 = malloc(sizeof(MATRIX));
        MATRIX* temp2 = malloc(sizeof(MATRIX));
        zero_matrix(n,n,temp1);
        zero_matrix(n,n,temp2);
        
        // The 7 important variable matrices of Strassens algorithm
        MATRIX* x1 = malloc(sizeof(MATRIX));
        MATRIX* x2 = malloc(sizeof(MATRIX));
        MATRIX* x3 = malloc(sizeof(MATRIX));
        MATRIX* x4 = malloc(sizeof(MATRIX));
        MATRIX* x5 = malloc(sizeof(MATRIX));
        MATRIX* x6 = malloc(sizeof(MATRIX));
        MATRIX* x7 = malloc(sizeof(MATRIX));
        zero_matrix(n,n,x1);
        zero_matrix(n,n,x2);
        zero_matrix(n,n,x3);
        zero_matrix(n,n,x4);
        zero_matrix(n,n,x5);
        zero_matrix(n,n,x6);
        zero_matrix(n,n,x7);
        
        // Fill those 7 matrices with the correct values
        add_matrices(a11, a22, temp1);
        add_matrices(b11, b22, temp2);
        strassen_helper(temp1, temp2, x1); 

        add_matrices(a21, a22, temp1);
        strassen_helper(temp1, b11, x2);

        subtract_matrices(b12, b22, temp2);
        strassen_helper(a11, temp2, x3);

        subtract_matrices(b21, b11, temp2);
        strassen_helper(a22, temp2, x4);

        add_matrices(a11, a12, temp1);
        strassen_helper(temp1, b22, x5);  

        subtract_matrices(a21, a11, temp1);
        add_matrices(b11, b12, temp2);      
        strassen_helper(temp1, temp2, x6);
        
        subtract_matrices(a12, a22, temp1);
        add_matrices(b21, b22, temp2);
        strassen_helper(temp1, temp2, x7);

        // 4 temporary result submatrices
        MATRIX* res11 = malloc(sizeof(MATRIX));
        MATRIX* res12 = malloc(sizeof(MATRIX));
        MATRIX* res21 = malloc(sizeof(MATRIX));
        MATRIX* res22 = malloc(sizeof(MATRIX));
        zero_matrix(n, n, res11);
        zero_matrix(n, n, res12);
        zero_matrix(n, n, res21);
        zero_matrix(n, n, res22);

        add_matrices(x3, x5, res12);
        add_matrices(x2, x4, res21);

        add_matrices(x1, x4, temp1);
        add_matrices(temp1, x7, temp2);
        subtract_matrices(temp2, x5, res11);

        add_matrices(x1, x3, temp1);
        add_matrices(temp1, x6, temp2);
        subtract_matrices(temp2, x2, res22);


        // Group submatrices
        for (int i=0; i<n; i++)
        {
            for (int j=0; j<n; j++)
            {
                // first matrix
                res->matrix[i][j] = res11->matrix[i][j];
                res->matrix[i][j+n] = res12->matrix[i][j];
                res->matrix[i+n][j] = res21->matrix[i][j];
                res->matrix[i+n][j+n] = res22->matrix[i][j];
            }
        }
        
        // Free all matrices.
        free_matrix(a11);
        free_matrix(a12);
        free_matrix(a21);
        free_matrix(a22);
        free_matrix(b11);
        free_matrix(b12);
        free_matrix(b21);
        free_matrix(b22);
        free_matrix(temp1);
        free_matrix(temp2);
        free_matrix(x1);
        free_matrix(x2);
        free_matrix(x3);
        free_matrix(x4);
        free_matrix(x5);
        free_matrix(x6);
        free_matrix(x7);
        free_matrix(res11);
        free_matrix(res12);
        free_matrix(res21);
        free_matrix(res22);
    }
}
Exemplo n.º 7
0
/* 
 * PURPOSE: run the commands which user entered 
 * INPUTS: 
 * cmd double pointer that holds all commands
 * mats the matrix list
 * num_mats the number of matrix in the list
 * RETURN: void
 * If no errors occurred during process then return nothing
 * else print error message
 **/
void run_commands (Commands_t* cmd, Matrix_t** mats, unsigned int num_mats) {
	//TODO ERROR CHECK INCOMING PARAMETERS
	if(!cmd){
		printf("commands array is null\n");
		return;
	}
	if(!(*mats)){
		printf("matrix list is null\n");
		return;
	}

	/*Parsing and calling of commands*/
	if (strncmp(cmd->cmds[0],"display",strlen("display") + 1) == 0
		&& cmd->num_cmds == 2) {
			/*find the requested matrix*/
			int idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
			if (idx >= 0) {
				display_matrix (mats[idx]);
			}
			else {
				printf("Matrix (%s) doesn't exist\n", cmd->cmds[1]);
				return;
			}
	}
	else if (strncmp(cmd->cmds[0],"add",strlen("add") + 1) == 0
		&& cmd->num_cmds == 4) {
			int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
			int mat2_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[2]);
			if (mat1_idx >= 0 && mat2_idx >= 0) {
				Matrix_t* c = NULL;
				if( !create_matrix (&c,cmd->cmds[3], mats[mat1_idx]->rows, 
						mats[mat1_idx]->cols)) {
					printf("Failure to create the result Matrix (%s)\n", cmd->cmds[3]);
					return;
				}
			
				if(add_matrix_to_array(mats,c, num_mats) == 999){
					perror("PROGRAM FAILED TO ADD MATRIX TO ARRAY\n");
					return;
				} //TODO ERROR CHECK NEEDED


				if (! add_matrices(mats[mat1_idx], mats[mat2_idx],c) ) {
					printf("Failure to add %s with %s into %s\n", mats[mat1_idx]->name, mats[mat2_idx]->name,c->name);
					return;	
				}
			}
	}
	else if (strncmp(cmd->cmds[0],"duplicate",strlen("duplicate") + 1) == 0
		&& cmd->num_cmds == 3 && strlen(cmd->cmds[1]) + 1 <= MATRIX_NAME_LEN) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		if (mat1_idx >= 0 ) {
				Matrix_t* dup_mat = NULL;
				if( !create_matrix (&dup_mat,cmd->cmds[2], mats[mat1_idx]->rows, 
						mats[mat1_idx]->cols)) {
					return;
				}
				if(!duplicate_matrix (mats[mat1_idx], dup_mat)){
					perror("PROGRAM FAILED TO DUPLICATE MATRIX\n");
					return;
				} //TODO ERROR CHECK NEEDED
				if(add_matrix_to_array(mats,dup_mat,num_mats) == 999){
					perror("PROGRAM FAILED TO ADD MATRIX TO ARRAY\n");
					return;
				} //TODO ERROR CHECK NEEDED
				printf ("Duplication of %s into %s finished\n", mats[mat1_idx]->name, cmd->cmds[2]);
		}
		else {
			printf("Duplication Failed\n");
			return;
		}
	}
	else if (strncmp(cmd->cmds[0],"equal",strlen("equal") + 1) == 0
		&& cmd->num_cmds == 2) {
			int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
			int mat2_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[2]);
			if (mat1_idx >= 0 && mat2_idx >= 0) {
				if ( equal_matrices(mats[mat1_idx],mats[mat2_idx]) ) {
					printf("SAME DATA IN BOTH\n");
				}
				else {
					printf("DIFFERENT DATA IN BOTH\n");
				}
			}
			else {
				printf("Equal Failed\n");
				return;
			}
	}
	else if (strncmp(cmd->cmds[0],"shift",strlen("shift") + 1) == 0
		&& cmd->num_cmds == 4) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		const int shift_value = atoi(cmd->cmds[3]);
		if (mat1_idx >= 0 ) {
			if(!bitwise_shift_matrix(mats[mat1_idx],cmd->cmds[2][0], shift_value)){
				perror("PROGRAM FAILED TO SHIFT MATRIX\n");
				return;
			} //TODO ERROR CHECK NEEDED
			printf("Matrix (%s) has been shifted by %d\n", mats[mat1_idx]->name, shift_value);
		}
		else {
			printf("Matrix shift failed\n");
			return;
		}

	}
	else if (strncmp(cmd->cmds[0],"read",strlen("read") + 1) == 0
		&& cmd->num_cmds == 2) {
		Matrix_t* new_matrix = NULL;
		if(! read_matrix(cmd->cmds[1],&new_matrix)) {
			printf("Read Failed\n");
			return;
		}	
		
		if(add_matrix_to_array(mats,new_matrix, num_mats) == 999){
			perror("PROGRAM FAILED TO ADD MATRIX TO ARRAY\n");
			return;
		} //TODO ERROR CHECK NEEDED
		printf("Matrix (%s) is read from the filesystem\n", cmd->cmds[1]);	
	}
	else if (strncmp(cmd->cmds[0],"write",strlen("write") + 1) == 0
		&& cmd->num_cmds == 2) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		if(! write_matrix(mats[mat1_idx]->name,mats[mat1_idx])) {
			printf("Write Failed\n");
			return;
		}
		else {
			printf("Matrix (%s) is wrote out to the filesystem\n", mats[mat1_idx]->name);
		}
	}
	else if (strncmp(cmd->cmds[0], "create", strlen("create") + 1) == 0
		&& strlen(cmd->cmds[1]) + 1 <= MATRIX_NAME_LEN && cmd->num_cmds == 4) {
		Matrix_t* new_mat = NULL;
		const unsigned int rows = atoi(cmd->cmds[2]);
		const unsigned int cols = atoi(cmd->cmds[3]);

		if(!create_matrix(&new_mat,cmd->cmds[1],rows, cols)){
			perror("PROGRAM FAILED TO ADD CREATE TO ARRAY\n");
			return;
		} //TODO ERROR CHECK NEEDED
		if(add_matrix_to_array(mats,new_mat,num_mats) == 999){
			perror("PROGRAM FAILED TO ADD MATRIX TO ARRAY\n");
			return;
		} // TODO ERROR CHECK NEEDED
		printf("Created Matrix (%s,%u,%u)\n", new_mat->name, new_mat->rows, new_mat->cols);
	}
	else if (strncmp(cmd->cmds[0], "random", strlen("random") + 1) == 0
		&& cmd->num_cmds == 4) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		const unsigned int start_range = atoi(cmd->cmds[2]);
		const unsigned int end_range = atoi(cmd->cmds[3]);
		if(!random_matrix(mats[mat1_idx],start_range, end_range)) {
			perror("PROGRAM FAILED TO RANDOMIZE MATRIX\n");
			return;
		} //TODO ERROR CHECK NEEDED

		printf("Matrix (%s) is randomized between %u %u\n", mats[mat1_idx]->name, start_range, end_range);
	}
	else {
		printf("Not a command in this application\n");
	}

}
Exemplo n.º 8
0
double moment ( int moment_n, double x[][3], double y[][3], double delta) {

    int n_steps     = 100;
    int phi_n_steps = 100;
    int i, j, n;
    int k, t, p;
    double value = 0.0;
    double delta_sq = delta*delta;
    double kappa, theta, phi;
    double kappa_step, theta_step, phi_step;
    double cosk, sink, costh, sinth;
    double surface_element, phi_contributn;
    
    double ATA     [4][4] = {{0.0}};
    double prev_ATA[4][4] = {{0.0}};
    double ATA_sum [4][4] = {{0.0}};
    double a[3] = {0.0}, b[3] = {0.0};
    double q[4] = {0.0};
    /**************/
    int construct_ATA (double ATA[4][4], double a[3],double b[3]);
    int add_matrices  (double matrix1[4][4],double matrix2[4][4],double result[4][4]);
    double braket     (double ATA[4][4], double q[4]);
    
    /* sum of A^TA matrices */
    for (n=0; n<moment_n; n++ ) {
	
	for (i=0; i<3; i++ ) {
	    a[i] = y[n][i] + x[n][i];
	    b[i] = y[n][i] - x[n][i];
	}
	construct_ATA (ATA, a, b);
	add_matrices (prev_ATA, ATA, ATA_sum);
	memcpy (prev_ATA[0], ATA_sum[0], 4*4*sizeof(double));
    }

    if (0) { /*check */

	q[0] = 1;
	for (i=0; i<4; i++ ) {
	    for (j=0; j<4; j++ ) {
		printf ("%8.3lf ", ATA_sum[i][j]);
	    }
	    printf ("\n");
	}
	printf ("\n");
	double aux, sum_sq = 0.0;;
	for (i=0; i<4; i++ ) {
	    aux = x[1][i]-y[1][i];
	    sum_sq +=  aux*aux;
	}
	printf ( " 00: %8.4le   %8.4le  %8.4le \n",
		 ATA_sum[0][0], braket(ATA_sum, q), sum_sq);
	exit(1);
    }

    
    value = 0.0;
    kappa_step = M_PI/n_steps;
    theta_step = M_PI/n_steps;
    phi_step   = 2*M_PI/phi_n_steps;
    
    /* for angles kappa, theta phi */
    for (k=1; k<=n_steps; k++) {
	kappa = ( (double)k-0.5)*kappa_step;
	cosk = cos(kappa);
	sink = sin(kappa);
	
	q[0] = cosk;
	
	for (t=1; t<=n_steps; t++) {
	    theta = ( (double)t-0.5)*theta_step;
	    sinth = sin (theta);
	    costh = cos (theta);

	    q[3] = sink*costh;
	    surface_element = sink*sink*sinth;
	    phi_contributn  = 0;
	    
	    for (p=1; p<=phi_n_steps; p++) {
		phi  = ((double)p-0.5)*phi_step;

		q[1] = sink*sinth*cos(phi); 
		q[2] = sink*sinth*sin(phi); 

		phi_contributn += exp(-braket(ATA_sum, q)/delta_sq);
		//value += sink*sink*sinth;
		//printf ( "%3d  %3d  %3d  %8.4le  %8.2le   --  %8.4le \n", k, t, p,
		//braket(ATA, q), exp(-braket(ATA, q)/delta_sq), phi_contributn);
	    }

	    value += phi_contributn*surface_element;
	}
    }
    
    value *= kappa_step*theta_step*phi_step; /*integration steps*/

    value /= 2*M_PI*M_PI; /* the function should return the average*/
    
    return value;
    
}
Exemplo n.º 9
0
int mappedCoords2rotation (double **x, double **y, int no_vectors,
			   double q[4], double **R, double T[3], double *rmsd) {

    double x_mp[3], y_mp[3];
    int  ctr;
     int  i, j;
 
    double ATA     [4][4] = {{0.0}};
    double prev_ATA[4][4] = {{0.0}};
    double ATA_sum [4][4] = {{0.0}};
    double a[3] = {0.0}, b[3] = {0.0};

    
    int add_matrices  (double matrix1[4][4],double matrix2[4][4],
		       double result[4][4]);
    int construct_ATA (double ATA[4][4], double a[3], double  b[3]);

    /* note how we pass the matrix: pointer to the first element in the block */
    void dsyev_ (char * jobz, char *uplo,  int *n,
		  double *A, int * lda, double * w, double * work, int * lwork, int *info);

    if (!no_vectors) {
	*rmsd = -1;
	return 1;
    }

    memset ( &(q[0]), 0, 4*sizeof(double) );
    /* turn the matching atoms into vectors x and y - use only c-alphas*/
     
    /* check: */
    if (0) {
	printf (" Number of vectors read in: %d. \n", no_vectors);
	for ( ctr =0; ctr < no_vectors; ctr++ ) {
	    printf ("\t x%1d   %10.4lf  %10.4lf  %10.4lf   ",
		    ctr, x[0][ctr], x[1][ctr], x[2][ctr]);
	    printf ("\t y%1d   %10.4lf  %10.4lf  %10.4lf \n",
		    ctr, y[0][ctr], y[1][ctr], y[2][ctr]);
	}
	exit (1);
    }

    /* find the meanpoints: */
    for ( i =0; i < 3; i++ ) {
	x_mp[i] = 0.0;
	y_mp[i] = 0.0;
    }
    for ( ctr =0; ctr < no_vectors; ctr++ ) {
	for ( i =0; i < 3; i++ ) {
	    x_mp[i] += x[i][ctr];
	    y_mp[i] += y[i][ctr];
	}
    }
    for ( i =0; i < 3; i++ ) {
	x_mp[i] /= no_vectors;
	y_mp[i] /= no_vectors;
    }
    /* subtract them from x, y */
    for ( ctr =0; ctr < no_vectors; ctr++ ) {
	for ( i =0; i < 3; i++ ) {
	    x[i][ctr] -= x_mp[i];
	    y[i][ctr] -= y_mp[i];
	}
    }
    /* B = ATA_sum matrix to diagonalize in order to get the quaternion */
    for ( ctr =0; ctr < no_vectors; ctr++ ) {
   	for (i=0; i<3; i++ ) {
	    a[i] = y[i][ctr] + x[i][ctr];
	    b[i] = y[i][ctr] - x[i][ctr];
	}
 	construct_ATA (ATA, a, b);
	add_matrices (prev_ATA, ATA, ATA_sum);
	memcpy (prev_ATA[0], ATA_sum[0], 4*4*sizeof(double));
    }
    for (i=0; i<4; i++ ) {
	for (j=0; j<4; j++ ) {
	    ATA_sum[i][j] /= no_vectors;
	}
    }
    /* diagonalize ATA_sum - the eigenvector corresponsing to the
       smallest lambda is the quaternion we are looking for; the
       eigenvalue is the rmsd*/
    /* use the nomenclature from dsyev*/
    char jobz= 'V'; /*Compute eigenvalues and eigenvectors.*/
    char uplo= 'U'; /* Upper triangle of A (the matrix we are diagonalizing) is stored; */
    int  n = 4;     /* order and the leading dimension of A */
    int  lda = 4;
    double ** A;
    int  info;
    int  lwork = 200;
    double w [4];
    double work[200];
    
    if ( !( A=dmatrix(4,4) ) ) exit (1);
    memcpy (A[0], ATA_sum[0], 4*4*sizeof(double));


   /* note how we pass the matrix: */
    dsyev_ ( &jobz, &uplo,  &n, A[0], &lda, w, work, &lwork, &info);
    if (  ! info) {
	*rmsd = sqrt (w[0]);
	for (i=0; i<4; i++ ) q[i] = A[0][i];
	if (0) {
	    /* w contains the eigenvalues */
	    printf ("\n");
	    for (i=0; i<4; i++ ) printf ("%8.3lf ", w[i]);
	    printf ("\nrmsd: %8.3lf \n", *rmsd);
	    printf ("quat:\n");
	    for (i=0; i<4; i++ ) printf ("%8.3lf ", q[i]);
	    printf ("\n");
	    /* printf (" opt lwork: %d\n", (int) work[0]); */
	}
    } else {
	fprintf (stderr, "Error in dsyev().\n");
	exit (1);
    }
    
    /* construct the rotation matrix R */
    quat_to_R (q,R);
    /* T = y_mp - R x_mp */
    for (i=0; i<3; i++ ) {
	T[i] = y_mp[i];
	for (j=0; j<3; j++ ) {
	    T[i] -= R[i][j]*x_mp[j];
	}
    }
   
    
    free_dmatrix(A);

 
    return 0;
}
Exemplo n.º 10
0
int main(void) {
  clock_t begin, end;
  double time_spent;
  begin = clock();

  matrix* a = create_matrix(4, 4);
  value temp_a[16] = { 18, 60, 57, 96,
		       41, 24, 99, 58,
		       14, 30, 97, 66,
		       51, 13, 19, 85 };
  insert_array(temp_a, a);

  matrix* b = create_matrix(4, 4);
  assert(insert_array(temp_a, b));


  //tests check_boundaries
  assert(check_boundaries(1,1,a));
  assert(check_boundaries(4,4,a));
  assert(!check_boundaries(4,5,a));
  assert(!check_boundaries(5,4,a));
  assert(!check_boundaries(0,1,a));
  assert(!check_boundaries(1,0,a));
  assert(!check_boundaries(-1,1,a));
  assert(!check_boundaries(1,-1,a));


  //tests compare_matrices,insert_value and get_value
  assert(compare_matrices(a,b));
  assert(insert_value(10,1,1,b));
  assert(!compare_matrices(a,b));
  assert(get_value(1,1,b)==10);
  assert(insert_value(18,1,1,b));
  assert(compare_matrices(a,b));


  //tests is_matrix
  matrix* c=a;
  assert(compare_matrices(a,c));
  assert(!is_matrix(a,b));
  assert(is_matrix(a,c));


  //tests insert_value by trying to go outside the matrix
  assert(insert_value(1,1,1,c));
  assert(insert_value(2,2,2,c));
  assert(insert_value(3,3,3,c));
  assert(insert_value(4,4,4,c));
  assert(!insert_value(5,5,5,c));
  assert(!insert_value(-1,-1,-1,c));
  assert(!insert_value(-1,-1,1,c));
  assert(!insert_value(-1,1,-1,c));

  //test get_value
  assert(get_value(1,1,c)==1);
  assert(get_value(2,2,c)==2);
  assert(get_value(3,3,c)==3);
  assert(get_value(4,4,c)==4);
  assert(get_value(0,0,c)==0);
  assert(get_value(1,-1,c)==0);
  assert(get_value(-1,1,c)==0);
  assert(get_value(5,5,c)==0);

  //tests insert and get without boundary checks
  insert_value_without_check(4,1,1,c);
  insert_value_without_check(3,2,2,c);
  insert_value_without_check(2,3,3,c);
  insert_value_without_check(1,4,4,c);
  assert(get_value_without_check(1,1,c)==4);
  assert(get_value_without_check(2,2,c)==3);
  assert(get_value_without_check(3,3,c)==2);
  assert(get_value_without_check(4,4,c)==1);

  //tests add_matrices
  value temp_b[16]={
    36,120,114,192,
    82,48,198,116,
    28, 60, 194,132,
    102,26,38,170};
  assert(insert_array(temp_b,a));
  matrix* d = create_matrix(4, 4);
  assert(add_matrices(b,b,d));
  assert(compare_matrices(d,a));

  //tests subtract_matrices
  value temp_c[16]={
    0,0,0,0,
    0,0,0,0,
    0, 0, 0,0,
    0,0,0,0};
  assert(insert_array(temp_c,a));
  assert(subtract_matrices(b,b,d));
  assert(compare_matrices(d,a));

  //tests sum_of_row
  assert(insert_array(temp_a,a));
  assert(sum_of_row(1,a)==231);
  assert(sum_of_row(4,a)==168);
  assert(sum_of_row(0,a)==0);
  assert(sum_of_row(5,a)==0);

  //tests sum_of_column
  assert(sum_of_column(1,a)==124);
  assert(sum_of_column(4,a)==305);
  assert(sum_of_column(0,a)==0);
  assert(sum_of_column(5,a)==0);

  //tests get_row_vector
  matrix* e = create_matrix(1, 4);
  value temp_d[4] = { 18, 60, 57, 96};
  assert(insert_array(temp_d,e));
  matrix* f = create_matrix(1, 4);
  assert(!get_row_vector(0,a,f));
  assert(!get_row_vector(5,a,f));
  assert(get_row_vector(1,a,f));
  assert(compare_matrices(e,f));

  //tests get_column_vector
  matrix* g = create_matrix(4, 1);
  assert(insert_array(temp_d,e));
  matrix* h = create_matrix(1, 4);
  assert(!get_row_vector(0,a,h));
  assert(!get_row_vector(5,a,h));
  assert(get_row_vector(1,a,h));
  assert(compare_matrices(e,h));

  //tests mulitply_matrices
  assert(multiply_matrices(a,a,b));
  value temp_f[16]={8478,5478,14319,17130,
		    6066,6760,15418,16792,
		    6206,5328,14431,15096,
		    6052,5047,7652,14129.00};
  assert(insert_array(temp_f,d));
  assert(compare_matrices(b,d));
  assert(!multiply_matrices(a,h,b));
  assert(!multiply_matrices(a,a,h));

  //tests transpose_matrix
  value temp_g[16]={18,41,14,51,
		    60,24,30,13,
		    57,99,97,19,
		    96,58,66,85};
  assert(insert_array(temp_g,d));
  assert(transpose_matrix(a,b));
  assert(compare_matrices(b,d));
  assert(!transpose_matrix(e,b));
  assert(!transpose_matrix(a,e));

  //tests multiply_matrix_with_scalar
  value temp_h[16] = { 36, 120, 114, 192,
		       82, 48, 198, 116,
		       28, 60, 194, 132,
		       102, 26, 38, 170 };
  assert(insert_array(temp_h,b));
  multiply_matrix_with_scalar(2,a);
  assert(compare_matrices(a,b));

  //test get_sub_matrix
  matrix* i=create_matrix(2,2);
  assert(insert_array(temp_a,a));
  assert(get_sub_matrix(1,2,1,2,a,i));
  matrix* j=create_matrix(2,2);
  value temp_i[4] = { 18, 60, 41, 24};
  assert(insert_array(temp_i,j));
  assert(compare_matrices(j,i));
  value temp_j[4] = { 97, 66, 19, 85};
  assert(insert_array(temp_j,j));
  assert(get_sub_matrix(3,4,3,4,a,i));
  assert(compare_matrices(j,i));
  assert(!get_sub_matrix(2,4,3,4,a,i));
  assert(!get_sub_matrix(3,4,2,4,a,i));
  assert(!get_sub_matrix(4,5,4,5,a,i));
  assert(!get_sub_matrix(0,1,0,1,a,i));

  //test insert_row_vector
  assert(insert_array(temp_a,a));
  value temp_k[16] = { 18, 60, 57, 96,
		       18, 60, 57, 96,
		       14, 30, 97, 66,
		       51, 13, 19, 85 };
  assert(insert_array(temp_k,b));
  assert(insert_array(temp_d,e));
  assert(insert_row_vector(2,e,a));
  assert(compare_matrices(a,b));

  end = clock();
  time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
  printf("time taken was: %f \n",time_spent);
  free_matrix(a);
  free_matrix(b);
  free_matrix(d);
  free_matrix(e);
  free_matrix(f);
  free_matrix(g);
  free_matrix(h);
  free_matrix(i);
  free_matrix(j);

  return 0;
}
Exemplo n.º 11
0
/*
* PURPOSE: Runs various commands for the operations to be performed on the matrices
* INPUTS: command array, matrix array, size of matrix array
* RETURN: Nothing
**/
void run_commands (Commands_t* cmd, Matrix_t** mats, unsigned int num_mats) {
	if(cmd == NULL || mats == NULL || num_mats <= 0)
		return;


	/*Parsing and calling of commands*/
	if (strncmp(cmd->cmds[0],"display",strlen("display") + 1) == 0
		&& cmd->num_cmds == 2) {
			/*find the requested matrix*/
			int idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
			if (idx >= 0) {
				display_matrix (mats[idx]);
			}
			else {
				printf("Matrix (%s) doesn't exist\n", cmd->cmds[1]);
				return;
			}
	}
	else if (strncmp(cmd->cmds[0],"add",strlen("add") + 1) == 0
		&& cmd->num_cmds == 4) {
			int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
			int mat2_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[2]);
			if (mat1_idx >= 0 && mat2_idx >= 0) {
				Matrix_t* c = NULL;
				if( !create_matrix (&c,cmd->cmds[3], mats[mat1_idx]->rows,
						mats[mat1_idx]->cols)) {
					printf("Failure to create the result Matrix (%s)\n", cmd->cmds[3]);
					return;
				}

				if(add_matrix_to_array(mats,c, num_mats) == -1){
					printf("Failed to add matrix to the array");
					return;
				}


				if (! add_matrices(mats[mat1_idx], mats[mat2_idx],c) ) {
					printf("Failure to add %s with %s into %s\n", mats[mat1_idx]->name, mats[mat2_idx]->name,c->name);
					return;
				}
			}
	}
	else if (strncmp(cmd->cmds[0],"duplicate",strlen("duplicate") + 1) == 0
		&& cmd->num_cmds == 3 && strlen(cmd->cmds[1]) + 1 <= MATRIX_NAME_LEN) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		if (mat1_idx >= 0 ) {
				Matrix_t* dup_mat = NULL;
				if( !create_matrix (&dup_mat,cmd->cmds[2], mats[mat1_idx]->rows,
						mats[mat1_idx]->cols)) {
					return;
				}

				if(duplicate_matrix (mats[mat1_idx], dup_mat) == false){
				 	printf("Duplication Failed\n");
					return;
				}

				if(add_matrix_to_array(mats,dup_mat,num_mats) == -1){
					printf("Failed to add matrix to array\n");
					return;
				}
				printf ("Duplication of %s into %s finished\n", mats[mat1_idx]->name, cmd->cmds[2]);
		}
		else {
			printf("Duplication Failed\n");
			return;
		}
	}
	else if (strncmp(cmd->cmds[0],"equal",strlen("equal") + 1) == 0
		&& cmd->num_cmds == 3) {
			int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
			int mat2_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[2]);
			if (mat1_idx >= 0 && mat2_idx >= 0) {
				if ( equal_matrices(mats[mat1_idx],mats[mat2_idx]) ) {
					printf("SAME DATA IN BOTH\n");
				}
				else {
					printf("DIFFERENT DATA IN BOTH\n");
				}
			}
			else {
				printf("Equal Failed\n");
				return;
			}
	}
	else if (strncmp(cmd->cmds[0],"shift",strlen("shift") + 1) == 0
		&& cmd->num_cmds == 4) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		const int shift_value = atoi(cmd->cmds[3]);
		if (mat1_idx <= 0 ) {
			printf("Matrix shift failed\n");
			return;
				}

		if(bitwise_shift_matrix(mats[mat1_idx],cmd->cmds[2][0], shift_value) == false){
				printf("Matrix shift failed\n");
				return;
		}
		else
			printf("Matrix (%s) has been shifted by %d\n", mats[mat1_idx]->name, shift_value);

		}
	else if (strncmp(cmd->cmds[0],"read",strlen("read") + 1) == 0
		&& cmd->num_cmds == 2) {
		Matrix_t* new_matrix = NULL;
		if(! read_matrix(cmd->cmds[1],&new_matrix)) {
			printf("Read Failed\n");
			return;
		}

		if(add_matrix_to_array(mats,new_matrix, num_mats) == -1){
			printf("Failed to add matrix to the array");
			;
		}
		printf("Matrix (%s) is read from the filesystem\n", cmd->cmds[1]);
	}
	else if (strncmp(cmd->cmds[0],"write",strlen("write") + 1) == 0
		&& cmd->num_cmds == 2) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		if(! write_matrix(mats[mat1_idx]->name,mats[mat1_idx])) {
			printf("Write Failed\n");
			return;
		}
		else {
			printf("Matrix (%s) is wrote out to the filesystem\n", mats[mat1_idx]->name);
		}
	}
	else if (strncmp(cmd->cmds[0], "create", strlen("create") + 1) == 0
		&& strlen(cmd->cmds[1]) + 1 <= MATRIX_NAME_LEN && cmd->num_cmds == 4) {
		Matrix_t* new_mat = NULL;
		const unsigned int rows = atoi(cmd->cmds[2]);
		const unsigned int cols = atoi(cmd->cmds[3]);

		if(create_matrix(&new_mat,cmd->cmds[1],rows, cols) == false){
			printf("Failed to create the matrix");
			return;
		}

		if(add_matrix_to_array(mats,new_mat,num_mats) == -1){
			printf("Failed to add matrix to the array");
			return;
		}
		printf("Created Matrix (%s,%u,%u)\n", new_mat->name, new_mat->rows, new_mat->cols);
	}
	else if (strncmp(cmd->cmds[0], "random", strlen("random") + 1) == 0
		&& cmd->num_cmds == 4) {
		int mat1_idx = find_matrix_given_name(mats,num_mats,cmd->cmds[1]);
		const unsigned int start_range = atoi(cmd->cmds[2]);
		const unsigned int end_range = atoi(cmd->cmds[3]);
		if(random_matrix(mats[mat1_idx],start_range, end_range) == false){
		 	printf("Failed to randomize\n");
			return;//TODO ERROR CHECK NEEDED
		}

		printf("Matrix (%s) is randomized between %u %u\n", mats[mat1_idx]->name, start_range, end_range);
	}
	else {
		printf("Not a command in this application\n");
	}

}
Exemplo n.º 12
0
int opt_quat ( double ** x, int NX, int *set_of_directions_x,
	       double ** y, int NY, int *set_of_directions_y,
	       int set_size, double * q, double * rmsd) {

    
    double * x_sub[set_size], * y_sub[set_size];
    int  ctr;
    int  i, j;
 
    double ATA     [4][4] = {{0.0}};
    double prev_ATA[4][4] = {{0.0}};
    double ATA_sum [4][4] = {{0.0}};
    double a[3] = {0.0}, b[3] = {0.0};
    
    int add_matrices  (double matrix1[4][4],double matrix2[4][4],
		       double result[4][4]);
    int construct_ATA (double ATA[4][4], double a[3], double  b[3]);

    /* note how we pass the matrix: pointer to the first element in the block */
    void dsyev_ (char * jobz, char *uplo,  int *n,
		  double *A, int * lda, double * w, double * work, int * lwork, int *info);

    if (!set_size) {
	*rmsd = -1;
	return 1;
    }

    memset ( &(q[0]), 0, 4*sizeof(double) );

    
    /* find the subset */
    ctr = 0;
    for ( ctr =0; ctr < set_size; ctr++ ) {
	x_sub[ctr] =  x[set_of_directions_x[ctr]];
	y_sub[ctr] =  y[set_of_directions_y[ctr]];
    }

    /* check: */
    if (0) {
	printf (" Number of vectors to match: %d. \n", set_size);
	for ( ctr =0; ctr < set_size; ctr++ ) {
	    printf ("\t x%1d   %10.4lf  %10.4lf  %10.4lf   ",
		    ctr, x_sub[ctr][0], x_sub[ctr][1], x_sub[ctr][2]);
	    printf ("\t y%1d   %10.4lf  %10.4lf  %10.4lf \n",
		    ctr, y_sub[ctr][0], y_sub[ctr][1], y_sub[ctr][2]);
	}
	exit (1);
    }

     
    /* B = ATA_sum matrix to diagonalize in order to get the quaternion */
    for ( ctr =0; ctr < set_size; ctr++ ) {
   	for (i=0; i<3; i++ ) {
	    a[i] = y_sub[ctr][i] + x_sub[ctr][i];
	    b[i] = y_sub[ctr][i] - x_sub[ctr][i];
	}
 	construct_ATA (ATA, a, b);
	add_matrices (prev_ATA, ATA, ATA_sum);
	memcpy (prev_ATA[0], ATA_sum[0], 4*4*sizeof(double));
    }
    for (i=0; i<4; i++ ) {
	for (j=0; j<4; j++ ) {
	    ATA_sum[i][j] /= set_size;
	}
    }
    /* diagonalize ATA_sum - the eigenvector corresponsing to the
       smallest lambda is the quaternion we are looking for; the
       eigenvalue is the rmsd*/
    /* use the nomenclature from dsyev*/
    char jobz= 'V'; /*Compute eigenvalues and eigenvectors.*/
    char uplo= 'U'; /* Upper triangle of A (the matrix we are diagonalizing) is stored; */
    int  n = 4;     /* order and the leading dimension of A */
    int  lda = 4;
    double ** A;
    int  info;
    int  lwork = 200;
    double w [4];
    double work[200];
    
    if ( !( A=dmatrix(4,4) ) ) exit (1);
    memcpy (A[0], ATA_sum[0], 4*4*sizeof(double));


   /* note how we pass the matrix: */
    dsyev_ ( &jobz, &uplo,  &n, A[0], &lda, w, work, &lwork, &info);
    if (  ! info) {
	*rmsd = sqrt (w[0]);
	for (i=0; i<4; i++ ) q[i] = A[0][i];
	if (0) {
	    /* w contains the eigenvalues */
	    printf ("\n");
	    for (i=0; i<4; i++ ) printf ("%8.3lf ", w[i]);
	    printf ("\nrmsd: %8.3lf \n", *rmsd);
	    printf ("quat:\n");
	    for (i=0; i<4; i++ ) printf ("%8.3lf ", q[i]);
	    printf ("\n");
	    /* printf (" opt lwork: %d\n", (int) work[0]); */
	}
    } else {
	fprintf (stderr, "Error in dsyev().\n");
	exit (1);
    }
    
   
    
    free_dmatrix(A);

    return 0;
    
}
Exemplo n.º 13
0
int main(void)
{
    int retval = 0;
    int choice = 0;
    short *prandom_data;
#ifdef PATCHED_1
    char m_result_data[MAX_ROWS * MAX_COLS * sizeof(int)];
#else
    char m_result_data[((MAX_ROWS * MAX_COLS) - 1) * sizeof(int)];
#endif

    prandom_data = create_random_shorts();
    matrix_t *m;
    matrix_t *m1, *m2;
    matrix_t *m_result;
    m1 = create_matrix(SHORT, NULL);
    m2 = create_matrix(SHORT, NULL);
    m_result = create_matrix(INT, m_result_data);

    char *input = malloc(2048);
    printf("Matrix math is fun!\n");
    printf("-------------------\n");
    while (1)
    {
        choice = select_menu_choice(input, LINE_SIZE);
        switch(choice)
        {
        case 1:
            printf("Inputting Matrix Values:\n");
            m = choose_matrix(m1, m2, input, LINE_SIZE);
            if (!m)
                goto cgc_exit;
            if (input_matrix(m, input, LINE_SIZE) == ERROR)
                goto cgc_exit;
            break;
        case 2:
            printf("Print Matrices:\n");
            print_matrices(m1, m2, m_result);
            break;
        case 3:
            printf("Adding Matrices:\n");
            add_matrices(m1, m2, m_result);
            break;
        case 4:
            printf("Subtracting Matrices:\n");
            subtract_matrices(m1, m2, m_result);
            break;
        case 5:
            printf("Multiplying Matrices:\n");
            multiply_matrices(m1, m2, m_result);
            break;
        case 6:
            printf("Swap Rows in a  Matrix:\n");
            m = choose_matrix(m1, m2, input, LINE_SIZE);
            if (!m)
                goto cgc_exit;
            retval = swap_matrix_row_col(m, SWAP_ROW, input, LINE_SIZE);
            if (retval == ERROR)
                goto cgc_exit;
            if (retval == SUCCESS)
                print_matrix("Swapped Rows", m);
            break;
        case 7:
            printf("Swap Columns in a  Matrix:\n");
            m = choose_matrix(m1, m2, input, LINE_SIZE);
            if (!m)
                goto cgc_exit;
            retval = swap_matrix_row_col(m, SWAP_COL, input, LINE_SIZE);
            if (retval == ERROR)
                goto cgc_exit;
            if (retval == SUCCESS)
                print_matrix("Swapped Columns", m);
            break;
        case 8:
            printf("Transpose a Matrix:\n");
            m = choose_matrix(m1, m2, input, LINE_SIZE);
            if (!m)
                goto cgc_exit;
            transpose_matrix(m);
            break;
        case 9:
            printf("Perform Reduced Row Echelon Form on Matrix\n");
            m = choose_matrix(m1, m2, input, LINE_SIZE);
            if (!m)
                goto cgc_exit;
            rref_matrix(m, m_result);
            break;
        case 10:
            printf("Create a Random Matrix:\n");
            m = choose_matrix(m1, m2, input, LINE_SIZE);
            if (!m)
                goto cgc_exit;
            if (random_matrix(m, input, LINE_SIZE, prandom_data) == ERROR)
                goto cgc_exit;
            break;
        case 11:
            goto cgc_exit;
        default:
            printf("Bad Selection\n");
        }
    }

cgc_exit:
    printf("Exiting...\n");
    return 0;
}