C++ Online Compiler
Example: Matrix Trace and Frobenius Norm Calculator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Matrix Trace and Frobenius Norm Calculator #include <iostream> #include <vector> #include <cmath> // For std::sqrt #include <iomanip> // For std::fixed and std::setprecision // Function to calculate the trace of a square matrix int calculateTrace(const std::vector<std::vector<int>>& matrix, int rows, int cols) { if (rows != cols) { return -1; // Indicate an error } int trace = 0; for (int i = 0; i < rows; ++i) { trace += matrix[i][i]; } return trace; } // Function to calculate the Frobenius norm of a matrix double calculateFrobeniusNorm(const std::vector<std::vector<int>>& matrix, int rows, int cols) { double sumOfSquares = 0.0; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { sumOfSquares += static_cast<double>(matrix[i][j]) * matrix[i][j]; } } return std::sqrt(sumOfSquares); } // Function to print the matrix void printMatrix(const std::vector<std::vector<int>>& matrix) { std::cout << "Matrix:" << std::endl; for (const auto& row : matrix) { for (int val : row) { std::cout << std::setw(3) << val << " "; // Set width for alignment } std::cout << std::endl; } std::cout << std::endl; } int main() { // Step 1: Define a sample matrix std::vector<std::vector<int>> myMatrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int numRows = myMatrix.size(); int numCols = myMatrix[0].size(); // Assumes matrix is not empty // Step 2: Print the matrix printMatrix(myMatrix); // Step 3: Calculate and display the trace int traceValue = calculateTrace(myMatrix, numRows, numCols); if (traceValue != -1) { std::cout << "Trace of the matrix: " << traceValue << std::endl; } else { std::cout << "Cannot calculate trace: Matrix is not square." << std::endl; } // Step 4: Calculate and display the Frobenius norm double normValue = calculateFrobeniusNorm(myMatrix, numRows, numCols); std::cout << std::fixed << std::setprecision(4); // Format output to 4 decimal places std::cout << "Frobenius Norm of the matrix: " << normValue << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS