C++ Online Compiler
Example: Calculate Matrix Frobenius Norm in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Calculate Matrix Frobenius Norm #include <iostream> #include <vector> #include <cmath> // For std::sqrt // 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; // Iterate through all elements of the matrix 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 the square root of the sum of squares return std::sqrt(sumOfSquares); } int main() { // Example matrix (3x3) std::vector<std::vector<int>> myMatrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int numRows = myMatrix.size(); int numCols = myMatrix[0].size(); // Calculate and print the Frobenius norm double normValue = calculateFrobeniusNorm(myMatrix, numRows, numCols); std::cout << "Frobenius Norm of the matrix: " << normValue << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS