Matrix Basics
Introduction to Matrices
A matrix is a rectangular array of numbers, symbols, or expressions arranged in rows and columns. In C++ programming, matrices are fundamental data structures used in various computational tasks, including linear algebra, machine learning, and scientific computing.
Matrix Representation in C++
Matrices can be represented using different data structures in C++:
1. 2D Vectors
std::vector<std::vector<double>> matrix = {
{1.0, 2.0, 3.0},
{4.0, 5.0, 6.0},
{7.0, 8.0, 9.0}
};
2. Raw 2D Arrays
double matrix[3][3] = {
{1.0, 2.0, 3.0},
{4.0, 5.0, 6.0},
{7.0, 8.0, 9.0}
};
Matrix Properties
Property |
Description |
Example |
Dimension |
Number of rows and columns |
3x3 matrix |
Symmetry |
Matrix equal to its transpose |
A = A^T |
Identity |
Matrix with 1s on diagonal |
[1 0 0; 0 1 0; 0 0 1] |
Basic Matrix Operations
Matrix Creation
class Matrix {
private:
std::vector<std::vector<double>> data;
int rows, cols;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data.resize(rows, std::vector<double>(cols, 0.0));
}
};
Accessing Matrix Elements
double getElement(int row, int col) {
return data[row][col];
}
void setElement(int row, int col, double value) {
data[row][col] = value;
}
Visualization of Matrix Structure
graph TD
A[Matrix] --> B[Rows]
A --> C[Columns]
B --> D[Row 1]
B --> E[Row 2]
B --> F[Row 3]
C --> G[Column 1]
C --> H[Column 2]
C --> I[Column 3]
Practical Considerations
When working with matrices in C++, consider:
- Memory efficiency
- Performance optimization
- Choosing appropriate data structures
- Error handling for matrix operations
LabEx recommends using modern C++ techniques and libraries like Eigen for advanced matrix computations.