Finding the Frobenius Norm of a given matrix
Last Updated :
24 Jun, 2022
Given an M * N matrix, the task is to find the Frobenius Norm of the matrix. The Frobenius Norm of a matrix is defined as the square root of the sum of the squares of the elements of the matrix.
Example:
Input: mat[][] = {{1, 2}, {3, 4}}
Output: 5.47723
sqrt(12 + 22 + 32 + 42) = sqrt(30) = 5.47723
Input: mat[][] = {{1, 4, 6}, {7, 9, 10}}
Output: 16.8226
Approach: Find the sum of squares of the elements of the matrix and then print the square root of the calculated value.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
const int row = 2, col = 2;
float frobeniusNorm( int mat[row][col])
{
int sumSq = 0;
for ( int i = 0; i < row; i++) {
for ( int j = 0; j < col; j++) {
sumSq += pow (mat[i][j], 2);
}
}
float res = sqrt (sumSq);
return res;
}
int main()
{
int mat[row][col] = { { 1, 2 }, { 3, 4 } };
cout << frobeniusNorm(mat);
return 0;
}
|
Java
class GFG
{
final static int row = 2 , col = 2 ;
static float frobeniusNorm( int mat[][])
{
int sumSq = 0 ;
for ( int i = 0 ; i < row; i++)
{
for ( int j = 0 ; j < col; j++)
{
sumSq += ( int )Math.pow(mat[i][j], 2 );
}
}
float res = ( float )Math.sqrt(sumSq);
return res;
}
public static void main (String[] args)
{
int mat[][] = { { 1 , 2 }, { 3 , 4 } };
System.out.println(frobeniusNorm(mat));
}
}
|
Python3
from math import sqrt
row = 2
col = 2
def frobeniusNorm(mat):
sumSq = 0
for i in range (row):
for j in range (col):
sumSq + = pow (mat[i][j], 2 )
res = sqrt(sumSq)
return round (res, 5 )
mat = [ [ 1 , 2 ], [ 3 , 4 ] ]
print (frobeniusNorm(mat))
|
C#
using System;
class GFG
{
static int row = 2, col = 2;
static float frobeniusNorm( int [,]mat)
{
int sumSq = 0;
for ( int i = 0; i < row; i++)
{
for ( int j = 0; j < col; j++)
{
sumSq += ( int )Math.Pow(mat[i, j], 2);
}
}
float res = ( float )Math.Sqrt(sumSq);
return res;
}
public static void Main ()
{
int [,]mat = { { 1, 2 }, { 3, 4 } };
Console.WriteLine(frobeniusNorm(mat));
}
}
|
Javascript
<script>
let row = 2, col = 2;
function frobeniusNorm(mat)
{
let sumSq = 0;
for (let i = 0; i < row; i++)
{
for (let j = 0; j < col; j++)
{
sumSq += parseInt(Math.pow(mat[i][j], 2));
}
}
let res = parseFloat(Math.sqrt(sumSq));
return res;
}
let mat = [[ 1, 2 ], [ 3, 4 ]];
document.write(frobeniusNorm(mat).toFixed(5));
</script>
|
Time Complexity: O(M*N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...