main(int argc, char* argv[]) {
int p[n], i, j, k;
double a[n][n], mu, t;

initmatrix(a, 5.0);
printmatrix(a);

for (k = 0; k<=n-2; k+=1) {
    p[k] = k;
    mu = abs(a[k][k]);
    for (i = k+1; i <= n-1; i+=1) {
      if (mu < abs(a[i][ k])) {
        mu = abs(a[i][k]);
        p[k] = i;
      }
    }

    for (j = k; j <= n-1; j+=1) {
       t = a[k][j];
       a[k][j] = a[p[k]][j];
       a[p[k]][j] = t;
    }

    for (i = k+1; i <= n-1; i+=1) {
          a[i][k] = a[i][k]/a[k][k];
    }
    for (j = k+1; j <=n-1; j+=1) {
       for (i = k+1; i <=n-1; i+=1) {
            a[i][j] = a[i][j] - a[i][k]*a[k][j];
       }
    }
 }

printmatrix(a);
}
Пример #2
0
int
main (void)
{
  float *u;
  float *s;
  float *v;

  size_t i;
  size_t j;

  svd_full (A, M, N, &u, &s, &v);
  assert (u != NULL);
  assert (s != NULL);
  assert (v != NULL);

  printmatrix ("u", u, M, N);
  printmatrix ("s", s, 1, N);
  printmatrix ("v", v, N, N);

  for (j = 0; j < N; j++) {
    assert (almostequalabs (S[j], s[j]));
    for (i = 0; i < M; i++)
      assert (almostequalabs (U[i * N + j], u[i * N + j]));
    for (i = 0; i < N; i++)
      assert (almostequalabs (V[i * N + j], v[i * N + j]));
  }
  mem_free (u);
  mem_free (s);
  mem_free (v);
  return EXIT_SUCCESS;
}
Пример #3
0
void modi(problem *p, matrix *x)
{
	matrix *rcost = newmatrix(p->angebot,p->nachfrage);
	nochmal:
	{
		tmatrix *m = newtmatrix(x);
		update_alphabeta(p,m);
		relcost(p,rcost);
		if(DEBUG)
		{
			printf("\nLoesung:\n");
			printmatrix(x);
			printf("\n\n");
			printf("Wahrheitsmatrix zu Loesung:\n");
			printtmatrix(m);
			printf("\n\n");
			printf("\nAlpha/Beta dazu:\n");
			print_alphabeta(p);
			printf("\n\n");
			printf("\nRelative Kosten dazu:\n");
			printmatrix(rcost);
			printf("\n\n");
		}
		int i=0,j=0,min=0,merker_i=0,merker_j=0;
		for(i=0; i < rcost->x; i++)
		{
			for(j=0; j < rcost->y; j++)
			{
				if(rcost->matrix[i*rcost->y+j] < min)
				{
					min = rcost->matrix[i*rcost->y+j];
					merker_i = i;
					merker_j = j;
				}
			}
		}
		if(min < 0)
		{
			node *n = newnode(merker_i,merker_j);
			if(findezyklus(n,m))
			{
				int mfluss = maxfluss(n,x,0,BIGINT);
				/* Basisloesung anpassen */
				aenderloesung(x,n,mfluss,0,0);
				goto nochmal;
			}
		}
	}
}
Пример #4
0
int main(int argc, char const *argv[])
{
	int C[] = {2, 1,2,3,4};
	int D[] = {2, 5,6,7,8};
	int E[] = {3, 1,2,3,4,5,6,7,8,9};
	int F[] = {3, 1,2,3,4,5,6,7,8,10};

	int *A = (int *) malloc(MATRIX_SIZE * MATRIX_SIZE + 1 * sizeof(int));
	int *B = (int *) malloc(MATRIX_SIZE * MATRIX_SIZE + 1 * sizeof(int));
	int *R = (int *) calloc(MATRIX_SIZE * MATRIX_SIZE + 1, sizeof(int));

	if (!A || !B || !R)
	{
		printf("Calloc error!\n");
		return 1;
	}

	fill_matrix(MATRIX_SIZE, A);
	fill_matrix(MATRIX_SIZE, B);
	multiply(E, F, R);
	printmatrix(R);

	free(A);
	free(B);
	free(R);
	return 0;
}
Пример #5
0
bool solvedMaze(int maze[N][N]) {
	int sol[N][N] = {{0,0,0,0},
					 {0,0,0,0},
					 {0,0,0,0},
					 {0,0,0,0}};
	if (maze[0][0]==0){
		printf("can't solve maze first element is blocked\n");
		return false;
	}
	if (cansolve(maze,sol,0,0)){
		printmatrix(sol);
		return true;
	} 			 
	else {
				printf("can't solve maze \n");
						printmatrix(sol);
				return false;
	} 	
}
Пример #6
0
  GLboolean
update_polhemus_state(void)
{
  polhemusvalstruct newpolhvals;
  vertype deltapos,deltaorient;
  GLboolean polhemus_moved,polhemus_rotated;
  ;
  read_polhemus(&newpolhvals);

  diffpos3d(polhemustate->pos,newpolhvals.pos,deltapos);
  diffpos3d(polhemustate->orient,newpolhvals.orient,deltaorient);

  polhemus_moved = !(vector_near_zero(deltapos,1.0));
  polhemus_rotated = !(vec_eq_zero(deltaorient));
  if (polhemus_moved)
  {
    copypos3d(newpolhvals.pos,polhemustate->pos);
    copypos3d(deltapos,polhemustate->deltapos);
  }
  if (polhemus_rotated)
  {
    copypos3d(newpolhvals.orient,polhemustate->orient);
    copypos3d(deltaorient,polhemustate->deltaorient);
  }
  if ((polhemus_moved || polhemus_rotated) && glove_state == Gloverotatestate)
    update_polh_xform();
#if 0
  printf("------------------------------------------------------------------\n");
  printf("X: %-6.0f Y: %-6.0f Z: %-6.0f   YAW: %-6.0f PITCH: %-6.0f ROLL: %-6.0f\n",
	 polhemustate->pos[vx],polhemustate->pos[vy],polhemustate->pos[vz],
	 polhemustate->orient[vx],
	 polhemustate->orient[vy],
	 polhemustate->orient[vz]);
  printf("thisxform:");
  printmatrix(polhemustate->xform);
  printf("deltaxform:");
  printmatrix(polhemustate->deltaxform);
#endif
#ifdef debugmalloc
  malloc_check();
#endif
  return(polhemus_moved);
}
Пример #7
0
void multiply(void){
	int i,j,k;

	for (j = 0; j < 4; j++)
		curr[j] = 0;

	for (j = 0; j < 4; j++)
		for (k = 0; k < 4; k++)
			curr[j] += start[k] * matrix[j][k];

	printmatrix();
}
Пример #8
0
void nqueen(int row) {
   int i, j;
   if (row < n) {
      for (i = 0; i < n; i++) {
         if (feasible(row, i)) {
            a[row][i] = 'Q';
            nqueen(row + 1);
            a[row][i] = '.';
         }
      }
   } else {
      printf("\nThe solution is:- ");
      printmatrix();
   }
}
Пример #9
0
int main(int argc, char** argv)
{
	int m=0, n=0, j, k, jx, kx;
	double* matrix;

	printf("Input the number of rows of the matrix: ");
	scanf("%d", &m);
	printf("Input the number of columns of the matrix: ");
	scanf("%d", &n);
	printf("Input the matrix[%d][%d]:\n", m, n);
	matrix = scanmatrix(m, n);
	
	printf("Printed matrix:\n");
	printmatrix(matrix, m, n);

	m = m > 0 ? m : 0;
	n = n > 0 ? n : 0;

	matrix = reallocmatrix(matrix, m, n, m+3, n+3);
	m += 3;
	n += 3;
	printf("Upsized matrix:\n");
	printmatrix(matrix, m, n);

	jx=m-2;
	kx=n-2;

	for(j=0; j<m; j++) {
		matrix[j+kx*m] = j;
	}
	for(k=0; k<n; k++) {
		matrix[jx+k*m] = k;
	}

	printf("Changed matrix:\n");
	printmatrix(matrix, m, n);

	matrix = cutOffRowJ(matrix, m--, n, jx);
	printf("Cut off row %d:\n", jx);
	printmatrix(matrix, m, n);

	matrix = cutOffColK(matrix, m, n--, kx);
	printf("Cut off col %d:\n", kx);
	printmatrix(matrix, m, n);

	matrix = reallocmatrix(matrix, m, n, m-2, n-2);
	m -= 2;
	n -= 2;
	printf("Downsized matrix:\n");
	printmatrix(matrix, m, n);

	matrix = freematrix(matrix);

	return EXIT_SUCCESS;
}
Пример #10
0
int main() {
	int i, j;

	printf("Matrix of integers (array of arrays of ints)\n");
	int intmatrix[3][5];
	for (i = 0; i < 3; i++) for (j = 0; j < 5; j++) intmatrix[i][j] = (i * 5) + j + 1;
	printmatrix(intmatrix, sizeof(**intmatrix), "%d", 3, 5, 5, 1);
	/* Note the double star in the sizeof (**), that's because we need the size of one pointer, not the size of an array of pointers. */

	printf("\n");

	printf("Dynamically allocated matrix of integers (array of ints)\n");
	int *dynintmatrix = calloc(3 * 5, sizeof(int));
	for (i = 0; i < 3 * 5; i++) dynintmatrix[i] = i + 1;
	printmatrix(dynintmatrix, sizeof(*dynintmatrix), "%d", 3, 5, 5, 1);
	free(dynintmatrix);

	printf("\n");

	printf("Array of integers (array of ints)\n");
	int intarray[3 * 5];
	for (i = 0; i < 3 * 5; i++) intarray[i] = i + 1;
	printmatrix(intarray, sizeof(*intarray), "%d", 3, 5, 5, 1);

	printf("\n");

	printf("String (array of chars)\n");
	char string[3 * 5] = "abcdefghijklmno";
	printmatrix(string, sizeof(*string), "%c", 3, 5, 5, 1);
	/* Note how %c is used, that's because every char is taken separately. */

	printf("\n");

	printf("Array of strings (array of pointers to arrays of chars)\n");
	char *stringarray[3 * 5]={"aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm", "nn", "oo"};
	printmatrix(stringarray, sizeof(*stringarray), "%s", 3, 5, 5, 1);

	printf("\n");

	printf("Matrix of strings (array of arrays of pointers to arrays of chars)\n");
	char *stringmatrix[3][5] = {
		{"aa", "bb", "cc", "dd", "ee"},
		{"ff", "gg", "hh", "ii", "jj"},
		{"kk", "ll", "mm", "nn", "oo"},
	};
	printmatrix(stringmatrix, sizeof(**stringmatrix), "%s", 3, 5, 5, 1);
	/* Note the double star in the sizeof (**), that's because we need the size of one pointer, not the size of an array of pointers. */

	printf("\n");

#ifdef _WIN32
	system("pause");
#endif
	return 0;
}
Пример #11
0
int matrixmult(int argc, char **argv, int what) {
  if(argc!=3) {
    cout << "Syntax: test1_01 " << what << " <matrix1> <matrix2>"<< endl;
    return 1;
  }
  
  matrix m1, m2;
  ifstream file1(argv[1]);
  ifstream file2(argv[2]);
  if(!read(file1, m1) ||  !read(file2,m2)) {
    cout << "Fehler beim einlesen der Dateien"<< endl;
    return 1;
  }

  printmatrix(m1*m2); // Hier passiert alles wichtige!

  return 0;
}
Пример #12
0
int polymatmult(int argc, char **argv, int what) {
  if(argc!=3) {
    cout << "Syntax: test1_01 " << what << " <polynom> <matrix2>"<< endl;
    return 1;
  }
  
  polynom p;
  matrix m;
  ifstream file1(argv[1]);
  ifstream file2(argv[2]);
  if(!read(file1, p) ||  !read(file2,m)) {
    cout << "Fehler beim einlesen der Dateien"<< endl;
    return 1;
  }

  printmatrix(p*m); // Hier passiert alles wichtige!

  return 0;
}
Пример #13
0
int main()
{
    int i, j;
    int array[100] = { [1 ... 99] = 0};
    for (i = 0; i < 100; i++)
    {
        printf("%c", array[i]);
    }

    /*
    int array[15][15];
    for (i = 0; i < 15; i++)
    {
            int array[i] = { [ 1 ... 14 ] = -1 };
    }

    for (i = 0; i < 15; i++)
    {
        for (j = 0; j < 15; j++)
        {
            printf("%i", array[i][j]);
        }
        printf("\n");
    }
    */

    char msweep[12][12] = {{'0'}};
    char user_chart[12][12] = {{'0'}};
/*
    for (i = 0; i < 12; i++)
    {
        for (j = 0; j < 12; j++)
        {
            msweep[i][j] = '0';
        }
    }
*/
    printmatrix(msweep, 12, user_chart);

}
Пример #14
0
void multiplyonce(void){
	static long long unsigned int tmp[4][4];
	int i, j, k;

	for (j = 0; j < 4; j++){
		for (i = 0; i < 4; i++){
			tmp[i][j] = matrix[i][j];
			matrix[i][j] = 0;
		}
	}

	for (i = 0; i < 4; i++){
		for (j = 0; j < 4; j++){
			for (k = 0; k < 4; k++){
				matrix[i][j] += orig[i][k] * tmp[k][j];
			}
			matrix[i][j] %= MOD;
		}
	}

	printmatrix();
}
Пример #15
0
void square(){
	static long long unsigned int tmp[4][4];
	int i, j, k;

	for (i = 0; i < 4; i++){
		for (j = 0; j < 4; j++){
			tmp[i][j] = matrix[i][j];
			matrix[i][j] = 0;
		}
	}

	for (i = 0; i < 4; i++){
		for (j = 0; j < 4; j++){
			for (k = 0; k < 4; k++){
				matrix[i][j] += tmp[i][k] * tmp[k][j];
			}
			matrix[i][j] %= MOD;
		}
	}

	printmatrix();
}
Пример #16
0
static void ambix_write_matrix(t_ambix_write *x, t_symbol*s, int argc, t_atom*argv) {
  int rows, cols;
  float32_t*data=NULL;
  int count;
  if(x->x_matrix)
    ambix_matrix_destroy(x->x_matrix);
  x->x_matrix=NULL;
  if(argc>=2) {
    rows=atom_getint(argv+0);
    cols=atom_getint(argv+1);
    argc-=2;
    argv+=2;
  } else {
    pd_error(x, "invalid matrix message");
    return;
  }
  if(argc!=rows*cols) {
    pd_error(x, "invalid matrix");
    return;
  }
  data=(float32_t*)malloc(rows*cols*sizeof(float32_t));
  for(count=0; count<argc; count++) {
    data[count]=atom_getfloat(argv+count);
  }

  x->x_matrix=ambix_matrix_init(rows, cols, x->x_matrix);
  if(AMBIX_ERR_SUCCESS!=ambix_matrix_fill_data(x->x_matrix, data)) {
    pd_error(x, "invalid matrix data [%dx%d]=%p", rows, cols, data);
    if(x->x_matrix)
      ambix_matrix_destroy(x->x_matrix);
    x->x_matrix=NULL;
  }
  free(data);

  if(x->x_matrix)
    printmatrix(x->x_matrix);
}
Пример #17
0
// ==========================================================================================================
int main () {
	int a[max][max],b[max][max],asmatrix[max][max];
	int k,n,c,z=0;
	 	switch(
	 	GetMenu((char *)"Input length square of Matrix , Maxtrix A,B;Plus 2 Maxtrix;Subtract 2 Matrix ;Multiplile 2 Matrix;Transpose Matrix;Addition feature for matrix",6)
	 	// GetMenu((char *)"Input length square of Matrix , Maxtrix A,B;Plus 2 Maxtrix  A+B;Subtract A-B;Multiplile A*B;Transpose Matrix",5)
	 	)
	 	{	case 1:z=1;do{printf("\tSize of matrix A & B (nxn) n : ");scanf("%d",&n); if(n>max) printf("\n\tPlease Input length < %d !\n",max);}while(n>max);definematrix(a,b,n);break;
	 		case 2:if(z==0){printf("\tPlease input matrix first\n");;break;}else{plus(a,b,asmatrix,n);print2matrix(a,b,n);printf("\tThe matrix After A+B or B+A is :\n"); printmatrix(asmatrix,n);}break;
	 		case 3:if(z==0){printf("\tPlease input matrix first\n");;break;}else{for(;;){c = GetMenu((char *)"A-B;B-A;Return to main menu",3);
	 			if(c == 0 )return 0;
	 			if(c == 1 ){subtract(a,b,asmatrix,n);print2matrix(a,b,n);printf("\tThe matrix After A-B is :\n"); printmatrix(asmatrix,n);}
	 			if(c == 2 ){subtract(b,a,asmatrix,n);print2matrix(b,a,n);printf("\tThe matrix After B-A is :\n"); printmatrix(asmatrix,n);}
	 			if(c == 3 )break;}}break;
	 		case 4:if(z==0){printf("\tPlease input matrix first\n");break;}else{for(;;){ c = GetMenu((char *)"A*B;B*A;Return to main menu",3);
	 			if(c == 0)	return 0;
	 			if(c == 1)	{multiplication(a,b,asmatrix,n);print2matrix(a,b,n);printf("\tThe matrix After A*B is :\n"); printmatrix(asmatrix,n);}
	 			if(c == 2)	{multiplication(b,a,asmatrix,n);print2matrix(b,a,n);printf("\tThe matrix After B*A is :\n"); printmatrix(asmatrix,n);}
	 			if(c == 3)	break;}}break;
	 		case 5:if(z==0){printf("\tPlease input matrix first\n");break;}else{
	 					for(;;){
	 					c = GetMenu((char *)"Transpose matrix A;Transpose matrix B;Return to main menu",3);
	 					if(c == 0) return 0;
	 					if(c == 1){transpose(a,asmatrix,n);printf("\tMatrix A (left) transpose of A (right) \n");print2matrix(a,asmatrix,n);}
	 		   			if(c == 2){transpose(b,asmatrix,n);printf("\tMatrix B (left) transpose of B (right) \n");print2matrix(b,asmatrix,n);}
	 					if(c == 3) break;
	 					
	 					}}break;
	 		case 6:if(z==0){printf("\tPlease input matrix first\n");break;}else{

	 			for(;;){c = GetMenu((char *)"Determinant A;Determinant B;Invert matrix A;Invert matrix B;Rank matrix A;Rank matrix B;Return to main menu",7);
	 					if(c == 0) return 0;
	 					if(c == 1) {printf("\n\tMatrix A :\n");printmatrix(a,n);printf("\n\tDeterminant Of A is %d\n",detmatrix(a,n));}
	 					if(c == 2) {printf("\n\tMatrix B :\n");printmatrix(b,n);printf("\n\tDeterminant Of B is %d\n",detmatrix(b,n));}
	 					if(c == 3){printf("\n\tMatrix A :\n");printmatrix(a,n);compmatrixtrans(a,asmatrix,n);if(detmatrix(a,n)!= 0){printf("\n\tInvert of A is \n");printinvert(asmatrix,a,n);}}
	 					if(c == 4){printf("\n\tMatrix B :\n");printmatrix(b,n);compmatrixtrans(b,asmatrix,n);if(detmatrix(b,n)!= 0){printf("\n\tInvert of B is \n");printinvert(asmatrix,b,n);}}
	 					if(c == 5){printf("\n\tMatrix A :\n");printmatrix(a,n);printf("\n\tRank Of A is %d\n",rankm(a,n));}
	 					if(c == 6) {printf("\n\tMatrix B :\n");printmatrix(b,n);printf("\n\tRank Of B is %d\n",rankm(b,n));}
	 					if(c == 7) break;
	 		}}break;	
	 		case 0:return 0;
	 }}}
Пример #18
0
int main(int argc, char *argv[])
{
  // Main function for the raytracer. Parses input parameters,
  // sets up the initial blank image, and calls the functions
  // that set up the scene and do the raytracing.
  struct image *im; // Will hold the raytraced image
  struct view *cam; // Camera and view for this scene
  int sx;   // Size of the raytraced image
  int antialiasing; // Flag to determine whether antialiaing is enabled or disabled
  char output_name[1024]; // Name of the output file for the raytraced .ppm image
  struct point3D e;   // Camera view parameters 'e', 'g', and 'up'
  struct point3D g;
  struct point3D up;
  double du, dv;      // Increase along u and v directions for pixel coordinates
  struct point3D pc,d;    // Point structures to keep the coordinates of a pixel and
        // the direction or a ray
  struct ray3D *ray;    // Structure to keep the ray from e to a pixel
  // struct colourRGB col;    // Return colour for raytraced pixels
  struct colourRGB background;   // Background colour
  int i,j;      // Counters for pixel coordinates
  unsigned char *rgbIm;

  if (argc<5)
  {
    fprintf(stderr,"RayTracer: Can not parse input parameters\n");
    fprintf(stderr,"USAGE: RayTracer size rec_depth antialias output_name\n");
    fprintf(stderr,"   size = Image size (both along x and y)\n");
    fprintf(stderr,"   rec_depth = Recursion depth\n");
    fprintf(stderr,"   antialias = A single digit, 0 disables antialiasing. Anything else enables antialiasing\n");
    fprintf(stderr,"   output_name = Name of the output file, e.g. MyRender.ppm\n");
    exit(0);
  }
  sx=atoi(argv[1]);
  MAX_DEPTH=atoi(argv[2]);
  if (atoi(argv[3])==0) antialiasing=0; else antialiasing=1;
    strcpy(&output_name[0],argv[4]);

  fprintf(stderr,"Rendering image at %d x %d\n",sx,sx);
  fprintf(stderr,"Recursion depth = %d\n",MAX_DEPTH);
  if (!antialiasing) fprintf(stderr,"Antialising is off\n");
  else  fprintf(stderr,"Antialising is on\n");
  fprintf(stderr,"Output file name: %s\n",output_name);

  object_list=NULL;
  light_list=NULL;
  texture_list=NULL;

  // Allocate memory for the new image
  im=newImage(sx, sx);
  if (!im)
  {
    fprintf(stderr,"Unable to allocate memory for raytraced image\n");
    exit(0);
  }
  else rgbIm=(unsigned char *)im->rgbdata;

  ///////////////////////////////////////////////////
  // TO DO: You will need to implement several of the
  //        functions below. For Assignment 3, you can use
  //        the simple scene already provided. But
  //        for Assignment 4 you need to create your own
  //        *interesting* scene.
  ///////////////////////////////////////////////////
  buildScene();   // Create a scene. This defines all the
      // objects in the world of the raytracer

  //////////////////////////////////////////
  // TO DO: For Assignment 3 you can use the setup
  //        already provided here. For Assignment 4
  //        you may want to move the camera
  //        and change the view parameters
  //        to suit your scene.
  //////////////////////////////////////////

  // Mind the homogeneous coordinate w of all vectors below. DO NOT
  // forget to set it to 1, or you'll get junk out of the
  // geometric transformations later on.

  // Camera center is at (0,0,-1)
  e.px=0;
  e.py=0;
  e.pz=-1;
  e.pw=1;

  // To define the gaze vector, we choose a point 'pc' in the scene that
  // the camera is looking at, and do the vector subtraction pc-e.
  // Here we set up the camera to be looking at the origin.
  g.px=0-e.px;
  g.py=0-e.py;
  g.pz=0-e.pz;
  g.pw=1;
  // In this case, the camera is looking along the world Z axis, so
  // vector w should end up being [0, 0, -1]

  // Define the 'up' vector to be the Y axis
  up.px=0;
  up.py=1;
  up.pz=0;
  up.pw=1;

  // Set up view with given the above vectors, a 4x4 window,
  // and a focal length of -1 (why? where is the image plane?)
  // Note that the top-left corner of the window is at (-2, 2)
  // in camera coordinates.
  cam=setupView(&e, &g, &up, -1, -2, 2, 4);

  if (cam==NULL)
  {
    fprintf(stderr,"Unable to set up the view and camera parameters. Our of memory!\n");
    cleanup(object_list,light_list, texture_list);
    deleteImage(im);
    exit(0);
  }

  // Set up background colour here
  background.R=0;
  background.G=0;
  background.B=0;

  // Do the raytracing
  //////////////////////////////////////////////////////
  // TO DO: You will need code here to do the raytracing
  //        for each pixel in the image. Refer to the
  //        lecture notes, in particular, to the
  //        raytracing pseudocode, for details on what
  //        to do here. Make sure you undersand the
  //        overall procedure of raytracing for a single
  //        pixel.
  //////////////////////////////////////////////////////
  du=cam->wsize/(sx-1);   // du and dv. In the notes in terms of wl and wr, wt and wb,
  dv=-cam->wsize/(sx-1);    // here we use wl, wt, and wsize. du=dv since the image is
        // and dv is negative since y increases downward in pixel
        // coordinates and upward in camera coordinates.
  colourRGB col;
  point3D origin;
  point3D direction;
  ray3D initialRay;
  colourRGB total;
  int offset;
  int aaSamples;
  fprintf(stderr,"View parameters:\n");
  fprintf(stderr,"Left=%f, Top=%f, Width=%f, f=%f\n",cam->wl,cam->wt,cam->wsize,cam->f);
  fprintf(stderr,"Camera to world conversion matrix (make sure it makes sense!):\n");
  printmatrix(cam->C2W);
  fprintf(stderr,"World to camera conversion matrix:\n");
  printmatrix(cam->W2C);
  fprintf(stderr,"\n");
  fprintf(stderr,"Rendering row: ");
  #pragma omp parallel for schedule(dynamic,32) shared(rgbIm, object_list, light_list, texture_list) private(j)
  for (j=0;j<sx;j++)    // For each of the pixels in the image
  // for (j=2;j<3;j++)
  {
    fprintf(stderr,"%d/%d, ",j,sx);
    #pragma omp parallel for private(origin, direction, col, initialRay, i, aaSamples, offset, total)
    for (i=0;i<sx;i++)
    // for (i=2;i<3;i++)
    {
      if (!antialiasing){
        col.R = 0;
        col.G = 0;
        col.B = 0;
        // = newPoint(cam->wl+i*du,cam->wt+j*dv,cam->f);
        origin.px = cam->wl+i*du;
        origin.py = cam->wt+j*dv;
        origin.pz = cam->f;
        origin.pw = 1.0;
        matVecMult(cam->C2W, &origin);
        // Construct direction vector using Pij - e
        // point3D direction;// = newPoint(origin->px,origin->py, origin->pz);
        direction.px = origin.px;
        direction.py = origin.py;
        direction.pz = origin.pz;
        direction.pw = 1.0;
        subVectors(&e, &direction);
        normalize(&direction);
        // Construct ray using both origin and direction.
        // ray3D initialRay;// = newRay(origin, direction);
        initialRay.p0 = origin;
        initialRay.d = direction;
        // Setting up colors.
        // col = (struct colourRGB *)calloc(1,sizeof(struct colourRGB));

        // Tracing ray
        rayTrace(&initialRay, 1, &col, NULL);
        offset = (sx * j * 3) + (i * 3);
        *(rgbIm + offset + 0) = col.R*255;
        *(rgbIm + offset + 1) = col.G*255;
        *(rgbIm + offset + 2) = col.B*255;
        // Tear down col struct.
        // free(col);
      } else {
        total.R = 0;
        total.G = 0;
        total.B = 0;
        for (aaSamples = 0; aaSamples < 20; aaSamples ++){
          col.R = 0;
          col.G = 0;
          col.B = 0;
          // point3D origin;// = newPoint(cam->wl+i*du,cam->wt+j*dv,cam->f);
          origin.px = cam->wl+(i+drand48()-0.5)*du;
          origin.py = cam->wt+(j+drand48()-0.5)*dv;
          origin.pz = cam->f;
          origin.pw = 1.0;
          matVecMult(cam->C2W, &origin);
          // Construct direction vector using Pij - e
          // point3D direction;// = newPoint(origin->px,origin->py, origin->pz);
          direction.px = origin.px;
          direction.py = origin.py;
          direction.pz = origin.pz;
          direction.pw = 1.0;
          subVectors(&e, &direction);
          normalize(&direction);
          // Construct ray using both origin and direction.
          // ray3D initialRay;// = newRay(origin, direction);
          initialRay.p0 = origin;
          initialRay.d = direction;
          // Setting up colors.
          // col = (struct colourRGB *)calloc(1,sizeof(struct colourRGB));
          // Tracing ray
          rayTrace(&initialRay, 1, &col, NULL);
          total.R += col.R;
          total.G += col.G;
          total.B += col.B;
        }
        offset = (sx * j * 3) + (i * 3);
        total.R = total.R / 20 * 255.0;
        total.G = total.G / 20 * 255.0;
        total.B = total.B / 20 * 255.0;
        *(rgbIm + offset + 0) = total.R;
        *(rgbIm + offset + 1) = total.G;
        *(rgbIm + offset + 2) = total.B;
      }
    } // end for i
  } // end for j
  
  fprintf(stderr,"\nDone!\n");

  // Output rendered image
  imageOutput(im,output_name);

  // Exit section. Clean up and return.
  cleanup(object_list,light_list,texture_list);   // Object, light, and texture lists
  deleteImage(im);          // Rendered image
  free(cam);            // camera view
  exit(0);
}
Пример #19
0
int main(void){
  double ma[6][3],mt[3][6],y[6],mm[3][3]={0},x[6],y2[3]={0};

  for(int i=0,j=2048;i<=5;i++,j*=2){
    x[i]=j;
  }
  
  y[0]=6.8820e+00 ;
  y[1]= 2.9064e+01 ;
  y[2]=1.1578e+02;
  y[3]=4.6309e+02;
  y[4]=1.8731e+03 ;
  y[5]=8.2617e+03 ;


  
  for(int i=0;i<6;i++){
    ma[i][0]=1;
    ma[i][1]=log(x[i]);
    ma[i][2]=x[i];
  }
   
  for(int i=0;i<6;i++){
    for(int j=0;j<3;j++){
      mt[j][i]=ma[i][j];
    }
  }
  n=6;
  m=3;
  printf("Ursprungsmatrix\n");
  printmatrix(ma,y);
  n=3;
  m=6;
  printf("Transponiert\n");
  printmatrix(mt,y);

  double sum;
  for(int i=0;i<3;i++){
    for(int j=0;j<3;j++){
      mm[i][j]=0;
      for(int k=0;k<6;k++){
        mm[i][j]+=mt[i][k]*ma[k][j];
      }
    }
  }

  for(int i=0;i<3;i++){
      y2[i]=0;
      for(int k=0; k<6;k++){
        y2[i]+=mt[i][k]*y[k];
      }
    
  }
      
  n=3;
  m=3;
  
  printf("Multipliziert\n");
  printmatrix(mm,y2);
  printf("gauss\n");
  gauss(mm,y2);
  printmatrix(mm,y2);
  calculatex(mm,y2);
}
Пример #20
0
/* encode an information word *
******************************/
void encode(graphs * graph, int *iphi, int *codeword, int gap, int verbose)
{
   int node, socket;

   int vnodenum, cnodenum;

   int row, col, temp;

   int *tempa, *tempb;

   vnodenum = (*graph).vnodenum;
   cnodenum = (*graph).cnodenum;

   /* allocate and clear temp */
   if (verbose)
      printf("allocate space\n");
   tempa = (int *)allocate(vnodenum * sizeof(int));
   tempb = (int *)allocate(vnodenum * sizeof(int));
   cleararray(tempa, vnodenum);
   cleararray(tempb, vnodenum);

   /* start by determining p1 */
   /* A s^T */
   graphmultiply(graph, 0, cnodenum - gap, 0, vnodenum - cnodenum, codeword, tempa);
   if (verbose)
   {
      printf("A s^T\n");
      printmatrix(tempa, 1, cnodenum - gap);
   }

   /* T^-1 A s^T */
   multiplybytminusone(graph, gap, tempa, tempb);
   if (verbose)
   {
      printf("T^-1 A s^T\n");
      printmatrix(tempb, 1, cnodenum - gap);
   }

   /* E (T^-1 A s^T) */
   cleararray(tempa, gap);
   graphmultiply(graph, cnodenum - gap, cnodenum,
                 vnodenum - cnodenum + gap, vnodenum, tempb, tempa);
   if (verbose)
   {
      printf("E (T^-1 A s^T) \n");
      printmatrix(tempa, 1, gap);
   }

   /* C s^T + E T^-1 A s^T */
   graphmultiply(graph, cnodenum - gap, cnodenum, 0, vnodenum - cnodenum, codeword, tempa);
   if (verbose)
   {
      printf("C s^T + E T^-1 A s^T \n");
      printmatrix(tempa, 1, gap);
   }

   /* phi^-1 (C s^T + E T^-1 A s^T) */
   for (row = 0; row < gap; row++)
      for (col = 0; col < gap; col++)
         codeword[row + vnodenum - cnodenum] ^= (*(iphi + row * gap + col) & tempa[col]);
   if (verbose)
   {
      printf("phi^-1 (C s^T + E T^-1 A s^T) \n");
      printmatrix(codeword, 1, vnodenum);
   }

   /* now determine p2 */
   /* A s^T + B p1^T */
   cleararray(tempa, vnodenum);
   graphmultiply(graph, 0, cnodenum - gap, 0, vnodenum - gap, codeword, tempa);
   if (verbose)
   {
      printf("A s^T + B p1^T \n");
      printmatrix(tempa, 1, cnodenum - gap);
   }

   /* T^-1 (A s^T + B p1^T) */
   multiplybytminusone(graph, gap, tempa, codeword + vnodenum - cnodenum + gap);
   if (verbose)
   {
      printf("T^-1 (A s^T + B p1^T) \n");
      printmatrix(codeword, 1, vnodenum);
   }

   /* make sure that all constraints are fulfilled */
   if (verbose)
      printf("make sure that all constraints are fulfilled \n");
   cleararray(tempa, vnodenum);
   graphmultiply(graph, 0, cnodenum, 0, vnodenum, codeword, tempa);
   for (node = 0; node < vnodenum; node++)
      assert(tempa[node] == 0);

   /* free allocated space */
   free(tempa);
   free(tempb);
}
Пример #21
0
VIO_BOOL extract_parameters_from_matrix(VIO_Transform *trans,
                                              double *center,
                                              double *translations,
                                              double *scales,
                                              double *shears,
                                              double *rotations)
{
  int 
    i,j;

  float 
    magnitude,
    **center_of_rotation,
    **result,
    **unit_vec,
    *ang,*tmp,
    **xmat,**T,**Tinv,**C,**Sinv,**R,**SR,**SRinv,**Cinv,**TMP1,**TMP2;

  ALLOC2D(xmat  ,5,5); nr_identf(xmat ,1,4,1,4);
  ALLOC2D(TMP1  ,5,5); nr_identf(TMP1 ,1,4,1,4);
  ALLOC2D(TMP2  ,5,5); nr_identf(TMP2 ,1,4,1,4);
  ALLOC2D(Cinv  ,5,5); nr_identf(Cinv ,1,4,1,4);
  ALLOC2D(SR    ,5,5); nr_identf(SR   ,1,4,1,4);
  ALLOC2D(SRinv ,5,5); nr_identf(SRinv,1,4,1,4);
  ALLOC2D(Sinv  ,5,5); nr_identf(Sinv ,1,4,1,4); 
  ALLOC2D(T     ,5,5); nr_identf(T    ,1,4,1,4);
  ALLOC2D(Tinv  ,5,5); nr_identf(Tinv ,1,4,1,4);
  ALLOC2D(C     ,5,5); nr_identf(C    ,1,4,1,4);
  ALLOC2D(R     ,5,5); nr_identf(R    ,1,4,1,4);

  ALLOC2D(center_of_rotation ,5,5);        /* make column vectors */
  ALLOC2D(result             ,5,5);
  ALLOC2D(unit_vec           ,5,5);

  ALLOC(tmp ,4);
  ALLOC(ang ,4);


  for(i=0; i<=3; i++)        /* copy the input matrix */
    for(j=0; j<=3; j++)
      xmat[i+1][j+1] = (float)Transform_elem(*trans,i,j);

  

  /* -------------DETERMINE THE TRANSLATION FIRST! ---------  */

                                /* see where the center of rotation is displaced... */

  FILL_NR_COLVEC( center_of_rotation, center[0], center[1], center[2] );


  invertmatrix(4, xmat, TMP1);        /* get inverse of the matrix */

  matrix_multiply( 4, 4, 1, xmat, center_of_rotation, result); /* was TMP! in place of xmat */

  SUB_NR_COLVEC( result, result, center_of_rotation );

  for(i=0; i<=2; i++) 
    translations[i] = result[i+1][1];

  /* -------------NOW GET THE SCALING VALUES! ----------------- */

  for(i=0; i<=2; i++) 
    tmp[i+1] = -translations[i];
  translation_to_homogeneous(3, tmp, Tinv); 

  for(i=0; i<=2; i++) 
    tmp[i+1] = center[i];
  translation_to_homogeneous(3, tmp, C); 
  for(i=0; i<=2; i++) 
    tmp[i+1] = -center[i];
  translation_to_homogeneous(3, tmp, Cinv); 


  matrix_multiply(4,4,4, xmat, C, TMP1);    /* get scaling*rotation matrix */


  matrix_multiply(4,4,4, Tinv, TMP1, TMP1);


  matrix_multiply(4,4,4, Cinv, TMP1,    SR);

  invertmatrix(4, SR, SRinv);        /* get inverse of scaling*rotation */

                                /* find each scale by mapping a unit vector backwards,
                                   and finding the magnitude of the result. */
  FILL_NR_COLVEC( unit_vec, 1.0, 0.0, 0.0 );
  matrix_multiply( 4, 4, 1, SRinv, unit_vec, result);
  magnitude = MAG_NR_COLVEC( result );
  if (magnitude != 0.0) {
    scales[0] = 1/magnitude;
    Sinv[1][1] = magnitude;
  }
  else {
    scales[0] = 1.0;
    Sinv[1][1] = 1.0;
  }

  FILL_NR_COLVEC( unit_vec, 0.0, 1.0, 0.0 );
  matrix_multiply( 4, 4, 1, SRinv, unit_vec, result);
  magnitude = MAG_NR_COLVEC( result );
  if (magnitude != 0.0) {
    scales[1] = 1/magnitude;
    Sinv[2][2] = magnitude;
  }
  else {
    scales[1]  = 1.0;
    Sinv[2][2] = 1.0;
  }

  FILL_NR_COLVEC( unit_vec, 0.0, 0.0, 1.0 );
  matrix_multiply( 4, 4, 1, SRinv, unit_vec, result);
  magnitude = MAG_NR_COLVEC( result );
  if (magnitude != 0.0) {
    scales[2] = 1/magnitude;
    Sinv[3][3] = magnitude;
  }
  else {
    scales[2] = 1.0;
    Sinv[3][3] = 1.0;
  }

  /* ------------NOW GET THE ROTATION ANGLES!----- */

                                /* extract rotation matrix */
  matrix_multiply(4,4, 4, Sinv, SR,   R);

                                /* get rotation angles */
  if (!rotmat_to_ang(R, ang)) {
    (void)fprintf(stderr,"Cannot convert R to radians!");
    printmatrix(3,3,R);
    return(FALSE);
  }

  for(i=0; i<=2; i++)
    rotations[i] = ang[i+1];


  FREE2D(xmat);
  FREE2D(TMP1);
  FREE2D(TMP2);
  FREE2D(Cinv);
  FREE2D(SR  );
  FREE2D(SRinv);
  FREE2D(Sinv);
  FREE2D(T   );
  FREE2D(Tinv);
  FREE2D(C   );
  FREE2D(R   );
  
  FREE2D(center_of_rotation);
  FREE2D(result            );
  FREE2D(unit_vec          );

  FREE(ang);
  FREE(tmp);

  return(TRUE);
}
Пример #22
0
int main(int argc, char **argv)
{
    double t;
    int i, j, n, p;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &n);
    MPI_Comm_rank(MPI_COMM_WORLD, &p);

    if (n != 2) {
        printf("Must be run on exactly 2 processors.\n");
        MPI_Finalize();
        return 1;
    }

    t = MPI_Wtime();

    /* Allocate an COLS * ROWS array. */
    float **matrix;
    matrix = alloc_floatmatrix(COLS, ROWS);

    /* Fill processor 1's matrix with numbers */
    for (i = 0; i < COLS; i++) {
        for ( j = 0; j < ROWS; j++) {
            matrix[i][j] = (i * 10) + j;
        }
    }

    /* Define two MPI_Datatypes for rows that we use later */
    MPI_Datatype fullrowtype, partrowtype;
    MPI_Type_vector(ROWS, 1, ROWS, MPI_FLOAT, &fullrowtype);
    MPI_Type_commit(&fullrowtype);
    MPI_Type_vector(3, 1, ROWS, MPI_FLOAT, &partrowtype);
    MPI_Type_commit(&partrowtype);

    if (p == 0) {
        MPI_Status s;

        zeromatrix(matrix);
        MPI_Recv(matrix[4], ROWS, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving column 4:", matrix);

        zeromatrix(matrix);
        MPI_Recv(&matrix[6][2], 4, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving column 6, rows 3-5:", matrix);

        zeromatrix(matrix);
        MPI_Recv(matrix[3], ROWS*2, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving column 3 and 4:", matrix);

        zeromatrix(matrix);
        MPI_Recv(matrix[0], ROWS*COLS, MPI_FLOAT, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving all columns:", matrix);

        zeromatrix(matrix);
        MPI_Recv(&matrix[0][6], 1, fullrowtype, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving row 6:", matrix);
       
        zeromatrix(matrix); 
        MPI_Recv(&matrix[0][1], 1, partrowtype, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving row 1 cols 0-2:", matrix);
        
        zeromatrix(matrix); 
        MPI_Recv(&matrix[4][1], 1, partrowtype, 1, 0, MPI_COMM_WORLD, &s);
        printmatrix("After receiving row 1 cols 4-6:", matrix);
    } else {
        /* Send all of column 4 to processor 0 */
        MPI_Send(matrix[4], ROWS, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send column 6 rows 2-5 to processor 0 */
        MPI_Send(&matrix[6][2], 4, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send columns 3 and 4 to processor 0 */
        MPI_Send(matrix[3], ROWS*2, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send the entire matrix (ie all columns) to processor 0 */
        MPI_Send(matrix[0], ROWS*COLS, MPI_FLOAT, 0, 0, MPI_COMM_WORLD);

        /* Send row 6 to processor 0 */
        MPI_Send(&matrix[0][6], 1, fullrowtype, 0, 0, MPI_COMM_WORLD);
        
        /* Send row 1 cols 0-2 to processor 0 */
        MPI_Send(&matrix[0][1], 1, partrowtype, 0, 0, MPI_COMM_WORLD);
        
        /* Send row 1 cols 4-6 to processor 0 */
        MPI_Send(&matrix[4][1], 1, partrowtype, 0, 0, MPI_COMM_WORLD);
    }
    if (p == 0) {
        t = MPI_Wtime() - t;
        printf("Program took %f secs to run.\n", t);
    }

    /* Free the matrix we allocated */
    free_matrix(matrix);

    /* Free the derived MPI_Datatypes */
    MPI_Type_free(&fullrowtype);
    MPI_Type_free(&partrowtype);

    MPI_Finalize();
    return 0;
}
Пример #23
0
// void determineiphi(graphs *graph, int gap, char *graphfile, int verbose)
void determineiphi(graphs * graph, encoders * encoder, char *graphfile, int verbose)
{
   int vnodenum, cnodenum;

   int row, col, node, socket;

   int temp, k;

   int *matrix, *extendedphi, *phi, *iphi;

   int gap;

   // copy encoders gap to internal gap for better readibility
   gap = (*encoder).gap;

   vnodenum = (*graph).vnodenum;
   cnodenum = (*graph).cnodenum;

   /* allocate memory */
   matrix = (int *)allocate(vnodenum * gap * sizeof(int));
   extendedphi = (int *)allocate(vnodenum * gap * sizeof(int));
   phi = (int *)allocate(gap * gap * sizeof(int));
   iphi = (int *)allocate(gap * gap * sizeof(int));

   /* clear matrix */
   for (row = 0; row < gap; row++)
      for (col = 0; col < vnodenum; col++)
         *(matrix + row * vnodenum + col) = 0;

   /* fill in the elements of the matrix */
   if (verbose)
      printf("copy the last %d rows of H into matrix\n", gap);
   for (node = cnodenum - gap; node < cnodenum; node++)
      for (socket = 0; socket < cnodedegree; socket++)
         *(matrix + (node - cnodenum + gap) * vnodenum + cnodeedge.dest) = 1;

   if (verbose)
   {
      printhmatrix(graph);
      printmatrix(matrix, gap, vnodenum);
   }

   /* perform gaussian elimination on the last gap rows */
   /* of the H matrix to clear E */
   if (verbose)
      printf("do gaussian elimination\n");
   node = cnodenum - gap - 1;
   for (col = vnodenum - 1; col > vnodenum - 1 - cnodenum + gap; col--)
   {
      for (row = 0; row < gap; row++)
      {
         if (*(matrix + row * vnodenum + col) == 1)
         {
            /* add the appropriate row of T */
            for (socket = 0; socket < cnodedegree; socket++)
               *(matrix + row * vnodenum + cnodeedge.dest) ^= 1;
         }

         if (verbose)
         {
            printhmatrix(graph);
            printmatrix(matrix, gap, vnodenum);
         }
      }

      node--;
   }

   /* next we need ensure that the submatrix */
   /* phi is not singular */
   /* first copy matrix into extended phi */
   for (row = 0; row < gap; row++)
      for (col = 0; col < vnodenum; col++)
         *(extendedphi + row * vnodenum + col) = *(matrix + row * vnodenum + col);

   row = -1;
   for (col = vnodenum - cnodenum + gap - 1; col > vnodenum - cnodenum - 1; col--)
   {
      row++;

      /* find a non zero entry */
      node = col;
      while (*(matrix + row * vnodenum + node) != 1)
      {
         node--;

         if (node < 0)
         {
            printf("H matrix is rank deficient!\n");
            exit(0);
         }
      }

      /* switch columns */
      switchvnode(graph, col, node);
      for (k = 0; k < gap; k++)
      {
         temp = *(matrix + k * vnodenum + node);
         *(matrix + k * vnodenum + node) = *(matrix + k * vnodenum + col);
         *(matrix + k * vnodenum + col) = temp;
      }
      for (k = 0; k < gap; k++)
      {
         temp = *(extendedphi + k * vnodenum + node);
         *(extendedphi + k * vnodenum + node) = *(extendedphi + k * vnodenum + col);
         *(extendedphi + k * vnodenum + col) = temp;
      }
      if (verbose)
      {
         printf("after switch\n");
         printmatrix(matrix, gap, vnodenum);
      }

      /* clear this column */
      for (k = row + 1; k < gap; k++)
      {
         if (*(matrix + k * vnodenum + col) == 1)
         {
            for (node = col; node >= 0; node--)
               *(matrix + k * vnodenum + node) ^= *(matrix + row * vnodenum + node);
         }
      }

      if (verbose)
      {
         printf("after addition\n");
         printmatrix(matrix, gap, vnodenum);
      }
   }

   /* we now know that phi is nonsingular */
   for (row = 0; row < gap; row++)
      for (col = vnodenum - cnodenum; col < vnodenum - cnodenum + gap; col++)
         *(phi + row * gap + col - vnodenum + cnodenum) = *(extendedphi + row * vnodenum + col);

   if (verbose)
   {
      printf("phi matrix\n");
      printmatrix(phi, gap, gap);
   }

   /* finally we need to determine the inverse of phi */
   inversematrix(phi, iphi, gap);

   /* store the inverse etc in the file */
   (*encoder).iphi = iphi;

   (*encoder).gap = gap;
   savegraph(graph, encoder, graphfile, 0);

   free(matrix);
   free(extendedphi);
   free(phi);
   free(iphi);
}
Пример #24
0
int main()
{
  int  m,n,p,i,j,comb,max;
  printf("Enter number of equations and variables\n");
  scanf("%d %d",&m,&n);
  p=n+1;
  float *optim=(float *)malloc(n*sizeof(float));
  float *blank=(float *)malloc(n*sizeof(float));
  float **mat = allocate(m,p);
  printf("Enter the coefficients of the equations\n");
  scanf("%*c");
  for(i=0;i<m;i++)
    {
      printf("Enter equation %d \n",i+1);
      for(j=0;j<p;j++)
	{
	  scanf("%f",(j+*(mat+i)));
	}
    }
  printf("The coefficient matrix is \n");
  printmatrix(mat,m,p);
  printf("\n");
  printf("Enter the function to be optimized \n");
  for(j=0;j<n;j++)
    {
      scanf("%f",optim+j);
    }
  printf("Enter 1 to maximize, 0 to minimize \n");
  scanf("%d",&max);
  
  comb =ncr(n,n-m);
  float **sols = allocate(comb,n);
  float **store = allocate(comb,n);
  float **temp = allocate(m,m+1);
  int *type=(int *)malloc(comb*sizeof(int));
  fill(blank,0,m,n,store);
  for( i=0;i<comb;i++)
    {
      int k=0,l;
      for(j=0;j<n;j++)
	{
	  if(fabs(store[i][j] - 1) < 0.001)
	    {
	     
	      for(l=0;l<m;l++)
		{
		  temp[l][k]=mat[l][j];
		}
	      k++;
	    }
	}
      for(l=0;l<m;l++)
	{
	  temp[l][k]=mat[l][n];
	}
      //printmatrix(temp,m,m+1);
      //  printf("\n");
      float * fs = (float *)malloc(m*sizeof(float));
     type[i]= gauss(temp,m,fs);
      k =0;
      for(j=0;j<n;j++)
	{
	  if(store[i][j] < 0.001)
	    {
	      sols[i][j]=0;
	    }
	  else
	    {
	      sols[i][j]=fs[k];
	      k++;
	    }
	}
    }
  //  printmatrix(sols,comb,n);
  printsolution(sols,m,n,type,optim,max);
  return 0;
}
Пример #25
0
int main(int argc, char** argv)
{
    int d;
    double **matr1, **matr2;
    int n1, n2;
    int m1, m2;
    FILE *fin1;        // первый исходный файл
    FILE *fin2;        // второй исходный файл
    FILE *fout1;       // файл для печати cуммы
    FILE *fout2;       // файл для печати произведения
    FILE *fout3;       // файл для печати матрицы, обратной к первой

    setlocale(0, "russian");

    if (argc < 6)
    {
        printf("Нет достаточного числа аргументов!");
        return BADARG;
    }
    fin1 = fopen(argv[1], "r");
    if (fin1 == NULL)
    {
        printf("Невозможно открыть первый исходный файл!");
        return BADINFILE1;
    }

    fin2 = fopen(argv[2], "r");
    if (fin2 == NULL)
    {
        fclose(fin1);
        printf("Невозможно открыть второй исходный файл!");
        return BADINFILE2;
    }

    fout1 = fopen(argv[3], "w");
    if (fout1 == NULL)
    {
        printf("Невозможно открыть файл результата #1!");
        fclose(fin1);
        fclose(fin2);
        return BADOUTFILE1;
    }

    fout2 = fopen(argv[4], "w");
    if (fout1 == NULL)
    {
        printf("Невозможно открыть файл результата #2!");
        fclose(fin1);
        fclose(fin2);
        return BADOUTFILE2;
    }

    fout3 = fopen(argv[5], "w");
    if (fout1 == NULL)
    {
        printf("Невозможно открыть файл результата #3!");
        fclose(fin1);
        fclose(fin2);
        return BADOUTFILE3;
    }

    if ((d = readmatrix(fin1, &matr1, &n1, &m1))!=0)
    {
        printf("Невозможно считать первую исходную матрицу!");
        fclose(fin1);
        fclose(fin2);
        fclose(fout1);
        fclose(fout2);
        fclose(fout3);
        switch (d)
        {
        case 1:
            printf("\nНеверная размерность!");
            return FAILEDDIM1;
        case 2:
            printf("\nНеверные тип и количество данных!");
            return FAILEDDATE1;
        case 3:
            printf("\nНевозможно выделить память под матрицу!");
            return FAILEDMEM1;
        }
    }

    if ((d = readmatrix(fin2, &matr2, &n2, &m2))!=0)
    {
        printf("Невозможно считать вторую исходную матрицу!");
        fclose(fin1);
        fclose(fin2);
        fclose(fout1);
        fclose(fout2);
        fclose(fout3);
        free_matrix(matr1, n1);
        switch (d)
        {
        case 1:
            printf("\nНеверная размерность!");
            return FAILEDDIM2;
        case 2:
            printf("\nНеверные тип и количество данных!");
            return FAILEDDATE2;
        case 3:
            printf("\nНевозможно выделить память под матрицу!");
            return FAILEDMEM2;
        }
    }
    double** sumst = summstr(matr1, n1, m1, matr2, n2, m2);
    if (sumst != NULL)
    {
        printmatrix(fout1, sumst, n1, m1);
        printf("\nCложение успешно!\n");
        free_matrix(sumst, n1);
    }
    else
        printf("\nНевозможно выполнить сложение!\n");

    double** mulst = multstr(matr1, n1, m1, matr2, n2, m2);
    if (mulst != NULL)
    {
        printmatrix(fout2, mulst, n1, m2);
        printf("\nУмножение успешно!\n");
        free_matrix(mulst, n1);
    }
    else
        printf("\nНевозможно выполнить умножение!\n");

    double** obrst = gaussobr(matr1, n1, m1);;
    if (obrst != NULL)
    {
        printmatrix(fout3, obrst, n1, m1);
        printf("\nОбратная матрица найдена успешно успешно!\n");
        free_matrix(obrst, n1);
    }
    else
        printf("\nНевозможно выполнить сложение!\n");

    fclose(fin1);
    fclose(fin2);
    fclose(fout1);
    fclose(fout2);
    free_matrix(matr1, n1);
    free_matrix(matr2, n2);
    return 0;
}
Пример #26
0
int main(void)
{
	int i=0;
	problem *p = readparameters(&nodes,&edges);
	if(!p) {
		printf("readparameters failed.");
		exit(1);
	}
	printf("Knoten:\t\t%4d\n  Angebot:\t%4d\n  Nachfrage:\t%4d\nKanten:\t\t%4d\n\n",nodes,p->angebot,p->nachfrage,edges);
	readgraph(p);
	printf("Kosten auf Kanten nach dem Einlesen:\n\n");
	printgraph(p);
	matrix *x = newmatrix(p->angebot,p->nachfrage);
	/* Solange noch Spalten oder Zeilen vorhanden, Kante waehlen,
	 * in die Basisloesung aufnehmen und Vogel-Werte neu berechnen. */
/*
	for(i=0; i < p->angebot+p->nachfrage-1; i++)
	{
		waehlekante_vogel(p,x);
		vogel(p);
	}
	printf("\n\nBasislösung nach Vogel:\n\n");
	printmatrix(x);

	p = readparameters(&nodes,&edges);
	readgraph(p);
	x = newmatrix(p->angebot,p->nachfrage);
*/


	for(i=0; i < p->angebot+p->nachfrage-1; i++)
	{
		waehlekante_nwe(p,x);
	}
	printf("\n\nBasislösung nach Nordwest-Ecken-Regel:\n\n");
	printmatrix(x);
	
/*
	p = readparameters(&nodes,&edges);
	readgraph(p);
	x = newmatrix(p->angebot,p->nachfrage);
	
	for(i=0; i < p->angebot+p->nachfrage-1; i++)
	{
		waehlekante_mkk(p,x);
	}
	printf("\n\nBasislösung nach Methode der kleinsten Kosten:\n\n");
	printmatrix(x);
	*/
	
	/* Stepping stone */
	/*
	stepstone(x,p);
	printf("\n\nBasislösung nach Stepping Stone:\n\n");
	printmatrix(x);
	*/
	
	/* Modi */
	modi(p,x);
	printf("\n\nBasislösung nach Modi:\n\n");
	printmatrix(x);

	return 0;
}
Пример #27
0
int main(int argc, char **argv) 
{
	if(DEBUG_ASM)
	{
		long C[] = {2, 1,2,3,4};
		long D[] = {2, 5,6,7,8};
		long R3[5];

		asm_inv_multiply(C, D, R3);
		printmatrix(R3);
	}
	else
	{	
		struct timeval start, stop;
		unsigned long long t, asm_tot = 0, asm_inv_tot = 0, c_tot = 0, c_inv_tot = 0, c_2_tot = 0;
		FILE *f = fopen("testr.txt", "a");

		long *A = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));
		long *B = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));
		long *R1 = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));
		long *R2 = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));
		long *R3 = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));
		long *R4 = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));
		long *R5 = (long *) malloc((MATRIX_SIZE * MATRIX_SIZE + 1) * sizeof(long));

		fill_matrix(MATRIX_SIZE, A);
		fill_matrix(MATRIX_SIZE, B);

		int i;
		for (i = 1; i <= NUM_RUNS; ++i)
		{
			fprintf(f,"Run %d, %s\n", i, RUN_INFO);
			printf("Run %d, %s\n", i, RUN_INFO);
			
			// Assembly
			gettimeofday(&start, NULL);
			asm_multiply(A, B, R1);
			gettimeofday(&stop, NULL);
			t = ((stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec) - start.tv_usec;
			asm_tot += t;
			fprintf(f,"Asm-func: %llu Microseconds\n", t);
			printf("Asm-func: %llu Microseconds\n", t);

			// Inverted assembly
			gettimeofday(&start, NULL);
			asm_inv_multiply(A, B, R2);
			gettimeofday(&stop, NULL);
			t = ((stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec) - start.tv_usec;
			asm_inv_tot += t;
			fprintf(f,"Asm-inv-func: %llu Microseconds\n", t);
			printf("Asm-inv-func: %llu Microseconds\n", t);

			// C
			gettimeofday(&start, NULL);
			c_multiply(A, B, R3);
			gettimeofday(&stop, NULL);
			t = ((stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec) - start.tv_usec;
			c_tot += t;
			fprintf(f,"C-func: %llu Microseconds\n", t);
			printf("C-func: %llu Microseconds\n", t);

			// Inverted C
			gettimeofday(&start, NULL);
			inv_c_multiply(A, B, R4);
			gettimeofday(&stop, NULL);
			t = ((stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec) - start.tv_usec;
			c_inv_tot += t;
			fprintf(f,"inv C-func: %llu Microseconds\n\n", t);
			printf("inv C-func: %llu Microseconds\n\n", t);

			// C 2
			gettimeofday(&start, NULL);
			c_multiply_2(A, B, R5);
			gettimeofday(&stop, NULL);
			t = ((stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec) - start.tv_usec;
			c_2_tot += t;
			fprintf(f,"C2-func: %llu Microseconds\n\n", t);
			printf("C2-func: %llu Microseconds\n\n", t);
		}

		fprintf(f,"Average on  %s\n", RUN_INFO);
		fprintf(f, "Asm-func average: %llu\n", asm_tot / NUM_RUNS);
		fprintf(f, "Asm-inv-func average: %llu\n", asm_inv_tot / NUM_RUNS);
		fprintf(f, "C-func average: %llu\n", c_tot / NUM_RUNS);
		fprintf(f, "C-inv-func average: %llu\n", c_inv_tot / NUM_RUNS);
		fprintf(f, "C2-func average: %llu\n\n________\n", c_2_tot / NUM_RUNS);

		fclose(f);
		validate_matrices(R1, R2, R3, R4);

		free(A);
		free(B);
		free(R1);
		free(R2);
		free(R3);
		free(R4);
	}
	return 0;	
}
Пример #28
0
void
main(void)
{
    int n = 3;
    int i, j, k;
    static double src[3][3] = {
	10.0, 1.0, 1.0,
	1.0, 1.0, 0.0,
	1.0, 0.0, 1.0,
    };
    static double dst[3][3], tmp[3][3];
    static double evec[3][3];
    static double eval[3];
    int nrot;

    for (i = 0; i < n; i++) {
	for (j = 0; j < n; j++) {
	    tmp[i][j] = src[i][j];
	}
    }

    printf("tmp0:\n");
    printmatrix(tmp);
    jacobi(tmp, eval, evec, &nrot);
    printf("tmp1:\n");
    printmatrix(tmp);

    for (i = 0; i < n; i++) {
	for (j = 0; j < n; j++) {
	    tmp[i][j] = 0.0;
	    for (k = 0; k < n; k++) {
		tmp[i][j] += src[i][k]*evec[k][j];
	    }
	}
    }
    printf("tmp2:\n");
    printmatrix(tmp);

#if 0
    for (i = 0; i < n; i++) {
	for (j = 0; j < n; j++) {
	    tmp[i][j] = evec[i][j]*eval[j];
	}
    }
    printf("tmp3:\n");
    printmatrix(tmp);
#endif

    for (i = 0; i < n; i++) {
	for (j = 0; j < n; j++) {
	    dst[i][j] = 0.0;
	    for (k = 0; k < n; k++) {
		dst[i][j] += evec[k][i]*tmp[k][j];
	    }
	}
    }

    printf("nrot: %d\n eval: %10.6f %10.6f %10.6f\n",
	   nrot, eval[0], eval[1], eval[2]);


    printf("src:\n");
    printmatrix(src);
    printf("\nevec:\n");
    printmatrix(evec);
    printf("\ndst:\n");
    printmatrix(dst);
    printf("\n");

}
Пример #29
0
/*
   function getparams will get the trnsform  parameters from a 
   transformation matrix 'tran' (that has already had the translation 
   componants removed).
   in description below, I assume that tran is a forward xform, from 
   native space to talairach space.
   I assume that trans is a 4x4 homogeneous matrix, with the 
   principal axis stored in the upper left 3x3 matrix.  The first col
   of tran represents is the coordinate of (1,0,0)' mapped through the
   transformation.  (this means  vec2 = tran * vec1).
  
   trans = [scale][shear][rot]
         = [scale][shear][rz][ry][rx];

   the shear matrix is constrained to be of the form:
     shear = [1 0 0 0
              f 1 0 0
              g h 1 0
              0 0 0 1];
     where f,g,h can take on any value.

   the scale matrix is constrained to be of the form:
     scale = [sx 0  0  0
              0  sy 0  0
              0  0  sz 0
              0  0  0  1];
     where sx,sy,sz must be positive.
   
  all rotations are assumed to be in the range -pi/2..pi/2

  the rotation angles are returned as radians and are applied 
  counter clockwise, when looking down the axis (from the positive end
  towards the origin).

  trans is assumed to be invertible.

  i assume a coordinate system:
             ^ y
             |
             |
             |
             |_______> x
            /
           /
          /z  (towards the viewer).

  
  
  procedure: 
          start with t = inv(tran) (after removing translation from tran )
  
          t = inv(r)*inv(sh)*inv(sc)
                  t maps the talairach space unit vectors into native
                space, which means that the columns of T are the
                direction cosines of these vectors x,y,z

   (1)  the length of the vectors x,y,z give the inverse scaling
        parameters:
             sx = 1/norm(x); sy = 1/norm(y); sz = 1/norm(z);

   (2)  with the constraints on the form of sh above, inv(sh) has the
        same form.  let inv(sh) be as above in terms of a,b and c.
          inv(sh) = [1 0 0 0; a 1 0 0; b c 1 0; 0 0 0 1];

        for c: project y onto z and normalize:

                  /     |y.z|^2     \(1/2)
             c = <  ---------------  >
                  \ |y|^2 - |y.z|^2 /

        for b: project x onto z and normalize

                  /        |x.z|^2        \(1/2)
             b = <  ---------------------  >
                  \ |x|^2 - |x.z|^2 - a^2 /
     
          where a is the projection of x onto the coordinate sys Y axis.

        for a: project x onto z and normalize
           a is taken from (b) above, and normalized... see below

  (3) rots are returned by getrots by giving the input transformation:
        rot_mat = [inv(sh)][inv(sc)][trans]

  (4) once completed, the parameters of sx,sy,sz and a,b,c are
      adjusted so that they maintain the matrix contraints above.


*/
VIO_BOOL extract2_parameters_from_matrix(VIO_Transform *trans,
                                               double *center,
                                               double *translations,
                                               double *scales,
                                               double *shears,
                                               double *rotations)
{
  int 
    i,j;

  float 
    n1,n2,
    magnitude, magz, magx, magy, ai,bi,ci,scalar,a1,
    **center_of_rotation,
    **result,
    **unit_vec,
    *ang,*tmp,**x,**y,**z, **nz, **y_on_z, **ortho_y,
    **xmat,**T,**Tinv,**C,**Sinv,
    **R,**SR,**SRinv,**Cinv,**TMP1,**TMP2;

  ALLOC2D(xmat  ,5,5); nr_identf(xmat ,1,4,1,4);
  ALLOC2D(TMP1  ,5,5); nr_identf(TMP1 ,1,4,1,4);
  ALLOC2D(TMP2  ,5,5); nr_identf(TMP2 ,1,4,1,4);
  ALLOC2D(Cinv  ,5,5); nr_identf(Cinv ,1,4,1,4);
  ALLOC2D(SR    ,5,5); nr_identf(SR   ,1,4,1,4);
  ALLOC2D(SRinv ,5,5); nr_identf(SRinv,1,4,1,4);
  ALLOC2D(Sinv  ,5,5); nr_identf(Sinv ,1,4,1,4); 
  ALLOC2D(T     ,5,5); nr_identf(T    ,1,4,1,4);
  ALLOC2D(Tinv  ,5,5); nr_identf(Tinv ,1,4,1,4);
  ALLOC2D(C     ,5,5); nr_identf(C    ,1,4,1,4);
  ALLOC2D(R     ,5,5); nr_identf(R    ,1,4,1,4);

  ALLOC2D(center_of_rotation ,5,5);        /* make column vectors */
  ALLOC2D(result             ,5,5);
  ALLOC2D(unit_vec           ,5,5);
  ALLOC2D(x                  ,5,5);
  ALLOC2D(y                  ,5,5);
  ALLOC2D(z                  ,5,5);
  ALLOC2D(nz                 ,5,5);
  ALLOC2D(y_on_z             ,5,5);
  ALLOC2D(ortho_y            ,5,5);

  ALLOC(tmp ,4);
  ALLOC(ang ,4);

  for(i=0; i<=3; i++)        /* copy the input matrix */
    for(j=0; j<=3; j++)
      xmat[i+1][j+1] = (float)Transform_elem(*trans,i,j);

  /* -------------DETERMINE THE TRANSLATION FIRST! ---------  */

                                /* see where the center of rotation is displaced... */

  FILL_NR_COLVEC( center_of_rotation, center[0], center[1], center[2] );


  invertmatrix(4, xmat, TMP1);        /* get inverse of the matrix */

  matrix_multiply( 4, 4, 1, xmat, center_of_rotation, result); /* was TMP! in place of xmat */

  SUB_NR_COLVEC( result, result, center_of_rotation );

  for(i=0; i<=2; i++) 
    translations[i] = result[i+1][1];

  /* -------------NOW GET THE SCALING VALUES! ----------------- */

  for(i=0; i<=2; i++) 
    tmp[i+1] = -translations[i];
  translation_to_homogeneous(3, tmp, Tinv); 

  for(i=0; i<=2; i++) 
    tmp[i+1] = center[i];
  translation_to_homogeneous(3, tmp, C); 
  for(i=0; i<=2; i++) 
    tmp[i+1] = -center[i];
  translation_to_homogeneous(3, tmp, Cinv); 


  matrix_multiply(4,4,4, xmat, C, TMP1);    /* get scaling*shear*rotation matrix */


  matrix_multiply(4,4,4, Tinv, TMP1, TMP1);


  matrix_multiply(4,4,4, Cinv, TMP1,    SR);

  invertmatrix(4, SR, SRinv);        /* get inverse of scaling*shear*rotation */

                                /* find each scale by mapping a unit vector backwards,
                                   and finding the magnitude of the result. */
  FILL_NR_COLVEC( unit_vec, 1.0, 0.0, 0.0 );
  matrix_multiply( 4, 4, 1, SRinv, unit_vec, result);
  magnitude = MAG_NR_COLVEC( result );
  if (magnitude != 0.0) {
    scales[0] = 1/magnitude;
    Sinv[1][1] = magnitude;
  }
  else {
    scales[0] = 1.0;
    Sinv[1][1] = 1.0;
  }

  FILL_NR_COLVEC( unit_vec, 0.0, 1.0, 0.0 );
  matrix_multiply( 4, 4, 1, SRinv, unit_vec, result);
  magnitude = MAG_NR_COLVEC( result );
  if (magnitude != 0.0) {
    scales[1] = 1/magnitude;
    Sinv[2][2] = magnitude;
  }
  else {
    scales[1]  = 1.0;
    Sinv[2][2] = 1.0;
  }

  FILL_NR_COLVEC( unit_vec, 0.0, 0.0, 1.0 );
  matrix_multiply( 4, 4, 1, SRinv, unit_vec, result);
  magnitude = MAG_NR_COLVEC( result );
  if (magnitude != 0.0) {
    scales[2] = 1/magnitude;
    Sinv[3][3] = magnitude;
  }
  else {
    scales[2] = 1.0;
    Sinv[3][3] = 1.0;
  }

  /* ------------NOW GET THE SHEARS, using the info from above ----- */

  /* SR contains the [scale][shear][rot], must multiply [inv(scale)]*SR
     to get shear*rot. */

                                /* make [scale][rot] */
  matrix_multiply(4,4, 4, Sinv, SR,  TMP1);

                                /* get inverse of [scale][rot] */
  invertmatrix(4, TMP1, SRinv);        


  FILL_NR_COLVEC(x, SRinv[1][1], SRinv[2][1], SRinv[3][1]);
  FILL_NR_COLVEC(y, SRinv[1][2], SRinv[2][2], SRinv[3][2]);
  FILL_NR_COLVEC(z, SRinv[1][3], SRinv[2][3], SRinv[3][3]);



                                /* get normalized z direction  */
  magz = MAG_NR_COLVEC(z);
  SCALAR_MULT_NR_COLVEC( nz, z, 1/magz );

                                /* get a direction perpendicular 
                                   to z, in the yz plane.  */
  scalar = DOTSUM_NR_COLVEC(  y, nz );
  SCALAR_MULT_NR_COLVEC( y_on_z, nz, scalar );

  SUB_NR_COLVEC( result, y, y_on_z ); /* result = y - y_on_z */
  scalar = MAG_NR_COLVEC( result);     /* ortho_y = result ./ norm(result)  */
  SCALAR_MULT_NR_COLVEC( ortho_y, result, 1/scalar);


                                /* GET C for the skew matrix */

  scalar = DOTSUM_NR_COLVEC( y, nz ); /* project y onto z */
  magy   = MAG_NR_COLVEC(y);
  ci = scalar / sqrt((double)( magy*magy - scalar*scalar)) ;
                                /* GET B for the skew matrix */

                                /*    first need a1 */

  a1     = DOTSUM_NR_COLVEC( x, ortho_y ); /* project x onto ortho_y */
  magx   = MAG_NR_COLVEC(x);

                                /*    now get B  */

  scalar = DOTSUM_NR_COLVEC( x, nz );
  bi = scalar / sqrt((double)( magx*magx - scalar*scalar - a1*a1)) ;

                                /* GET A for skew matrix  */

  ai = a1 / sqrt((double)( magx*magx - scalar*scalar - a1*a1));

                                /* normalize the inverse shear parameters.
                                   so that there is no scaling in the matrix 
                                   (all scaling is already accounted for 
                                   in sx,sy and sz. */

  n1 = sqrt((double)(1 + ai*ai + bi*bi));
  n2 = sqrt((double)(1 + ci*ci));

  ai = ai / n1;
  bi = bi / n1;
  ci = ci / n2;

                                /* ai,bi,c1 now contain the parameters for 
                                   the inverse NORMALIZED shear matrix 
                                   (i.e., norm(col_i) = 1.0). */

  
  /* ------------NOW GET THE ROTATION ANGLES!----- */

                                  /*  since SR = [scale][shear][rot], then
                                    rot = [inv(shear)][inv(scale)][SR] */

  nr_identf(TMP1 ,1,4,1,4);        /* make inverse scale matrix */
  TMP1[1][1] = 1/scales[0];
  TMP1[2][2] = 1/scales[1];
  TMP1[3][3] = 1/scales[2];

  nr_identf(TMP2 ,1,4,1,4);        /* make_inverse normalized shear matrix */
  TMP2[1][1] = sqrt((double)(1 - ai*ai - bi*bi));
  TMP2[2][2] = sqrt((double)(1 - ci*ci));
  TMP2[2][1] = ai;
  TMP2[3][1] = bi;
  TMP2[3][2] = ci;


                                /* extract rotation matrix */
  matrix_multiply(4,4, 4, TMP2, TMP1, T);
  matrix_multiply(4,4, 4, T,    SR,   R);

                                /* get rotation angles */
  if (!rotmat_to_ang(R, ang)) {
    (void)fprintf(stderr,"Cannot convert R to radians!");
    printmatrix(3,3,R);
    return(FALSE);
  }

  for(i=0; i<=2; i++)
    rotations[i] = ang[i+1];

  /* ------------NOW ADJUST THE SCALE AND SKEW PARAMETERS ------------ */

  invertmatrix(4, T, Tinv);        /* get inverse of the matrix */
  

  scales[0] = Tinv[1][1];
  scales[1] = Tinv[2][2];
  scales[2] = Tinv[3][3];
  shears[0] = Tinv[2][1]/scales[1] ;
  shears[1] = Tinv[3][1]/scales[2] ;
  shears[2] = Tinv[3][2]/scales[2] ;
  

  FREE2D(xmat);
  FREE2D(TMP1);
  FREE2D(TMP2);
  FREE2D(Cinv);
  FREE2D(SR  );
  FREE2D(SRinv);
  FREE2D(Sinv);
  FREE2D(T   );
  FREE2D(Tinv);
  FREE2D(C   );
  FREE2D(R   );
  
  FREE2D(center_of_rotation);
  FREE2D(result            );
  FREE2D(unit_vec          );
  FREE2D(x                 );
  FREE2D(y                 );
  FREE2D(z                 );
  FREE2D(nz                );
  FREE2D(y_on_z            );
  FREE2D(ortho_y           );

  FREE(ang);
  FREE(tmp);

  return(TRUE);
}
Пример #30
0
int main(int argc, char **argv)
{
  int rows=1,columns=1;
  int inplace=0;
  int nthreads=1;
  int runs=1;
  int print=0;
  if(argc==1)
  {
    printf("# usage: <program name> <rows> <columns> <inplace>\n");
    printf("# inplace should be 0 or 1 \n");
    return 0;
  }
  if(argc>1)
  {
    sscanf(argv[1],"%d",&rows);
  }
  if(argc>2)
  {
    sscanf(argv[2],"%d",&columns);
  }
  if(argc>3)
  {
    sscanf(argv[3],"%d",&inplace);
  }
  double wtime,avgtime;
  nthreads=omp_get_max_threads();
  printf("# Test program for transposing a Matrix with OpenMP\n");
  printf("# Number of avaliable Processors: %d\n",omp_get_num_procs());
/*  printf("# Number of Threads being used: %d\n",omp_get_max_threads());
  printf("Enter a number:");
  scanf("%d",&nthreads);
  printf("\n");*/
  fftw_complex*m1 = (fftw_complex *) malloc(sizeof(fftw_complex)*rows*columns);
  fftw_complex*m2 = (fftw_complex *) malloc(sizeof(fftw_complex)*rows*columns);
  initialize_matrix(m1,rows,columns);
  if(print==1) printmatrix(m1,rows,columns);
  if(inplace==1) 
  {
    int i=0;
    wtime=omp_get_wtime();
    for(i=0;i<runs;i++)
    {
      transpose_1(m1,rows,columns);
      /* this computation does not really make sense*/
    }
    wtime=omp_get_wtime()-wtime;
  }
  if(inplace==0) 
  {
    int i=0;
    wtime=omp_get_wtime();
    for(i=0;i<runs;i++)
    {
      transpose_2(m1,m2,rows,columns);
    }
    wtime=omp_get_wtime()-wtime;
  }
  if(inplace==3) 
  {
    int i=0;
    wtime=omp_get_wtime();
    for(i=0;i<runs;i++)
    {
      transpose_3(m1,rows,columns);
      /* this computation does not really make sense*/
    }
    wtime=omp_get_wtime()-wtime;
  }
  avgtime=wtime/runs;
  if(print==1) printmatrix(m1,rows,columns);
  printf("# Time for calculation used: %.6f\n",wtime);
  printf("# rows,columns,nthreads,inplace,runs,total time,avg time\n");
  printf("%d %d %d %d %d %.6f %.6f\n",rows,columns,nthreads,inplace,runs,wtime,avgtime);
 
  //  printmatrix(m1,rows,columns);
  /*struct timeval t1,t2;
  gettimeofday(&t1,NULL);
  gettimeofday(&t2,NULL);
  float seconds=t2.tv_sec-t1.tv_sec+(t2.tv_usec-t1.tv_usec)/1000000.0;
  printf("The measured time interval is %.6f seconds\n\n",seconds);*/
  free(m1);
  return 0;
}