# Frobenius Norm of a given matrix in C++

Hello guys, in this tutorial, we will learn how to find Frobenius Norm of a given matrix in C++. To do this, first, we calculate the squares of all elements in a given matrix and then add them to get a total. The Frobenius Norm of the given matrix equates to the square root of this total. For example,

A[2][2] = { {1, 3}, {2, 4} }

Frobenius Norm of A = sqrt(1^{2} + 3^{2} + 2^{2} + 4^{2}) = sqrt(30) = 5.477225

Now let’s write a C++ program that can calculate the Frobenius Norm of a matrix for us. See the example program below.

#include <iostream> #include <cmath> using namespace std; int main() { int r = 3, c = 3; int sum_of_sq = 0; int matrix[][3] = {{3, 6, 8}, {1, 7, 4}}; for(int i=0; i<r ;i++) { for(int j=0; j<c; j++) { sum_of_sq += (matrix[i][j] * matrix[i][j]); } } float out; out = sqrt(sum_of_sq); cout << "The Frobenius Norm of the given matrix is: " << out << endl; return 0; }

The output of the above is:

The Frobenius Norm of the given matrix is: 44.238

In the above program, we are using two loops to traverse every element in the matrix so that we can find its square and add it to the variable *sum_of_sq *which gives us the total sum of the square of elements of the matrix. We then find its square root using the built-in sqrt() method and print the result.

Let’s take a 2×2 matrix as input and find its Frobenius Norm using the above approach.

#include <iostream> #include <cmath> using namespace std; int main() { int r = 2, c = 2; int sum_of_sq = 0; int matrix[][2] = {{1, 3}, {2, 4}}; for(int i=0; i<r ;i++) { for(int j=0; j<c; j++) { sum_of_sq += (matrix[i][j] * matrix[i][j]); } } float out; out = sqrt(sum_of_sq); cout << "The Frobenius Norm of the given matrix is: " << out << endl; return 0; }

Output:

The Frobenius Norm of the given matrix is: 5.47723

Thank you.

Also read: Find normal and Trace of a matrix in C++

## Leave a Reply