Exemple #1
0
Matrix4x3 invertMatrix(const Matrix4x3 &m) {
	double w[3][8];

	for (int r = 0; r != 3; ++r) {
		for (int c = 0; c != 4; ++c) {
			w[r][c] = m(r, c);
			w[r][c+4] = (r == c) ? 1.0 : 0.0;
		}
	}

	if (w[0][0] == 0.0) {
		if (w[1][0] != 0.0)
			swapRows(w[0], w[1]);
		else
			swapRows(w[0], w[2]);
	}
	divideRow(w[0], w[0][0]);
	subtractRow(w[1], w[1][0], w[0]);
	subtractRow(w[2], w[2][0], w[0]);

	if (w[1][1] == 0.0)
		swapRows(w[1], w[2]);

	divideRow(w[1], w[1][1]);
	subtractRow(w[0], w[0][1], w[1]);
	subtractRow(w[2], w[2][1], w[1]);

	divideRow(w[2], w[2][2]);
	subtractRow(w[0], w[0][2], w[2]);
	subtractRow(w[1], w[1][2], w[2]);

	for (int r = 0; r != 3; ++r) {
		w[r][7] = -w[r][3];
		w[r][3] = 0.0;
	}

	Matrix4x3 result;

	for (int r = 0; r != 3; ++r)
		for (int c = 0; c != 4; ++c)
			result(r, c) = float(w[r][c+4]);

	return result;
}
Exemple #2
0
int main()
{
	/* Add your implementation here */
	int i;
	int j;
	int size;
	int colNum;
	int rowNum;
	char * pointless;
	double ** mat;
	char * input = getInput();
	if(strIsNum(input)){
		size = strtod(input, &pointless);//strToNum(input);
	}
	else
		sizeError();
	rowNum = size;
	colNum = size + 1;
	//Create matrix array
	mat = malloc(sizeof(double *) * rowNum);

	for(i = 0; i < size; i++){
		mat[i] = malloc(sizeof(double) * colNum);
		for(j = 0; j < colNum; j++){
			input = getInput();
			if((strlen(input) == 0)||!strIsNum(input))
				printMissingEl(i, j );
			else
				mat[i][j] = strtod(input, &pointless);
		}
	}
	printf("initial matrix\n");
	printMatrix(rowNum, colNum, mat);
	for(i = 0; i < rowNum; i++){
		int maxPos = i;
		//find the maximum value of abs(r[j][i]) where j >= i
		for(j = i + 1; j < rowNum; j++){
			if(fabs(mat[j][i]) > fabs(mat[maxPos][i])){
				maxPos = j;
			}
		}
		// this makes the pivot nonzero if possible
		int isSingular = 1;
		for(j = 0; j < rowNum; j++){
			if(mat[i][j] != 0){
				isSingular = 0;
				break;
			}
		}
		if(isSingular){
			printf("Error: Matrix is singular\n");
			exit(0);
		}			
		printf("swapped %d and %d\n", i, maxPos);
		swapRows(maxPos, i, mat);
		printMatrix(rowNum, colNum, mat);
		printf("row %d /= %f\n", i, mat[i][i]);
		divideRow(i, colNum, mat);
		printMatrix(rowNum, colNum, mat);
		for(j = 0; j < rowNum; j++){
			if(i != j){
				printf("row %d -= %f row %d\n", j, mat[j][i], i);
				makeZero(j, i, colNum, mat);
				printMatrix(rowNum, colNum, mat);
			}
		}
	}
	for(i = 0; i < rowNum; i++){
		printf("%f ",mat[i][size]);
	}
	printf("\n");
	return 0;
}