Matrix Manipulation
Basic Matrix Operations
Matrix Initialization
void initialize_matrix(int** matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * cols + j;
}
}
}
Core Matrix Operations
graph TD
A[Matrix Operations] --> B[Traversal]
A --> C[Transformation]
A --> D[Arithmetic]
A --> E[Advanced Computations]
Matrix Operation Types
Operation |
Description |
Complexity |
Traversal |
Accessing matrix elements |
O(rows * cols) |
Transpose |
Switching rows and columns |
O(rows * cols) |
Multiplication |
Matrix product calculation |
O(n³) |
Rotation |
Rotating matrix elements |
O(rows * cols) |
Matrix Traversal
void traverse_matrix(int** matrix, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
Matrix Transpose
int** transpose_matrix(int** matrix, int rows, int cols) {
int** transposed = create_matrix(cols, rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}
Matrix Multiplication
int** multiply_matrices(int** A, int** B, int rowsA, int colsA, int colsB) {
int** result = create_matrix(rowsA, colsB);
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
result[i][j] = 0;
for (int k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
Advanced Matrix Techniques
Matrix Rotation
void rotate_matrix_90_degrees(int** matrix, int rows, int cols) {
// In-place 90-degree clockwise rotation
for (int layer = 0; layer < rows / 2; layer++) {
int first = layer;
int last = rows - 1 - layer;
for (int i = first; i < last; i++) {
int offset = i - first;
int top = matrix[first][i];
// Left -> Top
matrix[first][i] = matrix[last-offset][first];
// Bottom -> Left
matrix[last-offset][first] = matrix[last][last-offset];
// Right -> Bottom
matrix[last][last-offset] = matrix[i][last];
// Top -> Right
matrix[i][last] = top;
}
}
}
- Use cache-friendly access patterns
- Minimize memory allocations
- Leverage SIMD instructions
- Consider parallel processing
Error Handling Techniques
int validate_matrix_operation(int** matrix, int rows, int cols) {
if (matrix == NULL || rows <= 0 || cols <= 0) {
fprintf(stderr, "Invalid matrix parameters\n");
return 0;
}
return 1;
}
Best Practices
- Use efficient memory layouts
- Minimize redundant computations
- Implement robust error checking
- Choose appropriate data types
Note: LabEx provides comprehensive resources for mastering matrix manipulation techniques in C programming.