Table of Contents
Matrix
Work with matrices.
Read matrix
static int** readMatrix2D(istream &is, int w, int h ) { int i, j; int ** matrix; matrix = new int * [h]; for ( i = 0; i < h; i ++ ) { matrix[i] = new int [w]; for ( j =0; j < w; j ++ ) { cin >> matrix[i][j]; } } return ( matrix ); }
Alloc matrix
static int ** allocMatrix2D(int rows, int cols ){ int** matrix; matrix = new int * [ rows ]; for (int i = 0; i < rows; i ++ ){ matrix[i] = new int [cols]; } return ( matrix ); }
Copy matrix
static int ** copyMatrix2D(int ** matrix, int ** matrix2, int rows, int cols){ for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] =matrix2[i][j]; } } return(matrix2); }
Enlarge matrix
static int ** enlargeMatrix(int ** matrix, int rows, int cols, int newRows, int newCols){ int **newMatrix; newMatrix=allocMatrix(newRows,newCols); copyMatrix(matrix,newMatrix,rows,cols); return (newMatrix); }
Free matrix
static void freeMatrix2D(int ** matrix, int rows ){ for (int i = 0; i < rows; i ++ ){ delete [] matrix[i]; } delete [] matrix; }
Transpose matrix
static int ** transposeMatrix( int ** mat, int w, int h ) { int i, j; int ** res; res = new int * [w]; // src w -> dst h for ( i = 0; i < w; i ++ ) { res[i] = new int [h]; for ( j = 0; j < h; j ++ ) res[i][j] = mat[j][i]; } return res; }
Upper triangle
static int upperTriangle ( int ** mat, int w, int h ) { int i, j, k; int tmp, mul; for ( i = 0; i < h; i ++ ) { if ( mat[i][i] == 0 ) { for ( j = i + 1; j < h; j ++ ) if ( mat[j][i] != 0 ) break; if ( j >= h ) return ( TRIANG_ERR ); for ( k = 0; k < w; k ++ ) { tmp = mat[i][k]; mat[i][k] = mat[j][k]; mat[j][k] = tmp; } } for ( j = i + 1; j < h; j ++ ) { mul = mat[j][i]; for ( k = 0; k < w; k ++ ) mat[j][k] = mat[j][k] * mat[i][i] - mul * mat[i][k]; } } return ( TRIANG_OK ); }
Print matrix
static void printMatrix2D(int ** matrix, int w, int h ) { int i, j; for ( i = 0; i < h; i ++ ) { if ( i == 0 ) cout << "/"; else if ( i == h-1) cout << "\\"; else cout << "|"; for ( j = 0; j < w; j ++ ) { if ( j ) cout << " "; cout << setw ( 7 ) << matrix[i][j]; } if ( i == 0 ) cout << "\\"; else if ( i == h-1) cout << "/"; else cout << "|"; cout << endl; } cout << endl; }