C++ Program to Find the Normal and Trace of Matrix
17/06/2024To find the normal and trace of a matrix, we need to understand the definitions of these terms:
- Trace of a Matrix: The trace of a square matrix is the sum of the elements on its main diagonal (from the upper left to the lower right).
- Normal of a Matrix: The normal (or Frobenius norm) of a matrix is the square root of the sum of the squares of all its elements.
Problem Statement
Given a square matrix, compute its trace and normal.
Approach
- Trace Calculation: Sum the diagonal elements of the matrix.
- Normal Calculation: Compute the sum of the squares of all elements in the matrix, then take the square root of this sum.
Example
For a 3×3 matrix:
Matrix:
1 2 3
4 5 6
7 8 9
- Trace: 1+5+9=15
- Normal: √{1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2} = √285 ≈ 16.88
C++ Code Implementation
Here is a C++ program to compute the trace and normal of a matrix:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// Function to compute the trace of a matrix
int traceOfMatrix(const vector<vector<int>>& matrix) {
int trace = 0;
for (size_t i = 0; i < matrix.size(); ++i) {
trace += matrix[i][i];
}
return trace;
}
// Function to compute the normal (Frobenius norm) of a matrix
double normalOfMatrix(const vector<vector<int>>& matrix) {
double sumOfSquares = 0.0;
for (const auto& row : matrix) {
for (const auto& elem : row) {
sumOfSquares += elem * elem;
}
}
return sqrt(sumOfSquares);
}
// Function to print a matrix
void printMatrix(const vector<vector<int>>& matrix) {
for (const auto& row : matrix) {
for (const auto& elem : row) {
cout << elem << ” “;
}
cout << endl;
}
}
int main() {
// Initializing a 3×3 matrix
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
cout << “Matrix:” << endl;
printMatrix(matrix);
// Computing the trace of the matrix
int trace = traceOfMatrix(matrix);
cout << “Trace of the matrix: ” << trace << endl;
// Computing the normal of the matrix
double normal = normalOfMatrix(matrix);
cout << “Normal (Frobenius norm) of the matrix: ” << normal << endl;
return 0;
}
Explanation
- Function traceOfMatrix:
- Parameters: Takes a 2D vector (matrix).
- Trace Calculation: Iterates through the diagonal elements (where row index equals column index) and sums them.
- Return Value: Returns the computed trace.
- Function normalOfMatrix:
- Parameters: Takes a 2D vector (matrix).
- Normal Calculation: Iterates through all elements of the matrix, calculates the sum of their squares, and returns the square root of this sum.
- Return Value: Returns the computed normal.
-
Function printMatrix:
Prints the matrix in a formatted way for better visualization.
-
Main Function:
- Initializes a sample 3×3 matrix.
- Prints the matrix.
- Calls the traceOfMatrix function to compute the trace and prints it.
- Calls the normalOfMatrix function to compute the normal and prints it.