Skip to content
Related Articles

Related Articles

Improve Article
Variance and standard-deviation of a matrix
  • Difficulty Level : Hard
  • Last Updated : 06 Apr, 2021

Prerequisite – Mean, Variance and Standard Deviation, Variance and Standard Deviation of an array
Given a matrix of size n*n. We have to calculate variance and standard-deviation of given matrix. 
Examples : 
 

Input : 1 2 3
        4 5 6
        6 6 6 
Output : variance: 3
         deviation: 1

Input : 1 2 3
        4 5 6
        7 8 9 
Output : variance: 6
         deviation: 2  

Explanation: 
First mean should be calculated by adding sum of each elements of the matrix. After calculating mean, it should be subtracted from each element of the matrix.Then square each term and find out the variance by dividing sum with total elements. 
Deviation: It is the square root of the variance.
Example: 
 

      1 2 3
      4 5 6
      7 8 9

Here mean is 5 and variance is approx 6.66
 

Below is code implementation:
 

C++




// CPP program to find mean and
// variance of a matrix.
#include <bits/stdc++.h>
using namespace std;
 
// variance function declaration
int variance(int, int, int);
 
// Function for calculating mean
int mean(int a[][3], int n)
{
    // Calculating sum
    int sum = 0;
    for (int  i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            sum += a[i][j];
     
    // Returning mean
    return sum / (n * n);
}
 
// Function for calculating variance
int variance(int a[][3], int n, int m)
{
    int sum = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
 
            // subtracting mean from elements
            a[i][j] -= m;
 
            // a[i][j] = fabs(a[i][j]);
            // squaring each terms
            a[i][j] *= a[i][j];
        }
    }
 
    // taking sum
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            sum += a[i][j];   
 
    return sum / (n * n);
}
 
// driver program
int main()
{
    // declaring and initializing matrix
    int mat[3][3] = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 } };
 
    // for mean
    int m = mean(mat, 3);
 
    // for variance
    int var = variance(mat, 3, m);
 
    // for standard deviation
    int dev = sqrt(var);
 
    // displaying variance and deviation
     cout << "Mean: " << m << "\n"
          << "Variance: " << var << "\n"
          << "Deviation: " << dev << "\n";
    return 0;
}

Java




// Java program to find mean
// and variance of a matrix.
import java.io.*;
 
class GFG
{
// Function for
// calculating mean
static int mean(int a[][],
                int n)
{
    // Calculating sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            sum += a[i][j];
     
    // Returning mean
    return sum / (n * n);
}
 
// Function for
// calculating variance
static int variance(int a[][],
                    int n, int m)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
 
            // subtracting mean
            // from elements
            a[i][j] -= m;
 
            // a[i][j] = fabs(a[i][j]);
            // squaring each terms
            a[i][j] *= a[i][j];
        }
    }
 
    // taking sum
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            sum += a[i][j];
 
    return sum / (n * n);
}
 
// Driver Code
public static void main (String[] args)
{
 
// declaring and
// initializing matrix
int mat[][] = {{1, 2, 3},
               {4, 5, 6},
               {7, 8, 9}};
 
// for mean
int m = mean(mat, 3);
 
// for variance
int var = variance(mat, 3, m);
 
// for standard
// deviation
double dev = (int)Math.sqrt(var);
 
// displaying variance
// and deviation
System.out.println("Mean: " + m);
System.out.println("Variance: " +
                            var);
System.out.println("Deviation: " +
                        (int)dev);
}
}
 
// This code is contributed
// by akt_mit

Python3




# Python3 program to find mean
# and variance of a matrix.
import math;
 
# variance function declaration
# Function for calculating mean
def mean(a, n):
 
    # Calculating sum
    sum = 0;
    for i in range(n):
        for j in range(n):
            sum += a[i][j];
     
    # Returning mean
    return math.floor(int(sum / (n * n)));
 
# Function for calculating variance
def variance(a, n, m):
    sum = 0;
    for i in range(n):
        for j in range(n):
 
            # subtracting mean
            # from elements
            a[i][j] -= m;
 
            # a[i][j] = fabs(a[i][j]);
            # squaring each terms
            a[i][j] *= a[i][j];
 
    # taking sum
    for i in range(n):
        for j in range(n):
            sum += a[i][j];
 
    return math.floor(int(sum / (n * n)));
 
# Driver Code
 
# declaring and
# initializing matrix
mat = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]];
 
# for mean
m = mean(mat, 3);
 
# for variance
var = variance(mat, 3, m);
 
# for standard deviation
dev = math.sqrt(var);
 
# displaying variance
# and deviation
print("Mean:", m);
print("Variance:", var);
print("Deviation:", math.floor(dev));
 
# This code is contributed by mits

C#




// C# program to find mean
// and variance of a matrix.
using System;
 
class GFG
{
     
// Function for
// calculating mean
static int mean(int [,]a,
                int n)
{
    // Calculating sum
    int sum = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            sum += a[i, j];
     
    // Returning mean
    return sum / (n * n);
}
 
// Function for
// calculating variance
static int variance(int [,]a,
                    int n, int m)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
 
            // subtracting mean
            // from elements
            a[i, j] -= m;
 
            // a[i][j] = fabs(a[i][j]);
            // squaring each terms
            a[i, j] *= a[i, j];
        }
    }
 
    // taking sum
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            sum += a[i,j];
 
    return sum / (n * n);
}
 
// Driver Code
static public void Main ()
{
 
// declaring and
// initializing matrix
int [,]mat = {{1, 2, 3},
              {4, 5, 6},
              {7, 8, 9}};
 
// for mean
int m = mean(mat, 3);
 
// for variance
int var = variance(mat, 3, m);
 
// for standard deviation
double dev = (int)Math.Sqrt(var);
 
// displaying variance and deviation
Console.WriteLine("Mean: " + m );
    Console.WriteLine("Variance: " + var);
    Console.WriteLine("Deviation: " + dev);
}
}
 
// This code is contributed by ajit

PHP




<?php
// PHP program to find mean
// and variance of a matrix.
 
// variance function declaration
// Function for calculating mean
function mean($a, $n)
{
    // Calculating sum
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
        for ( $j = 0; $j < $n; $j++)
            $sum += $a[$i][$j];
     
    // Returning mean
    return floor((int)$sum / ($n * $n));
}
 
// Function for calculating variance
function variance($a, $n, $m)
{
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
    {
        for ($j = 0; $j < $n; $j++)
        {
 
            // subtracting mean
            // from elements
            $a[$i][$j] -= $m;
 
            // a[i][j] = fabs(a[i][j]);
            // squaring each terms
            $a[$i][$j] *= $a[$i][$j];
        }
    }
 
    // taking sum
    for ($i = 0; $i < $n; $i++)
        for ( $j = 0; $j < $n; $j++)
            $sum += $a[$i][$j];
 
    return floor((int)$sum / ($n * $n));
}
 
// Driver Code
 
// declaring and
// initializing matrix
$mat = array(array(1, 2, 3),
             array(4, 5, 6),
             array(7, 8, 9));
 
// for mean
$m = mean($mat, 3);
 
// for variance
$var = variance($mat, 3, $m);
 
// for standard deviation
$dev = sqrt($var);
 
// displaying variance
// and deviation
echo "Mean: " , $m , "\n",
     "Variance: " , $var ,
      "\n", "Deviation: " ,
        floor($dev) , "\n";
 
// This code is contributed by ajit
?>

Javascript




<script>
 
// JavaScript program to find mean
// and variance of a matrix
 
// Function for
// calculating mean
function mean(a, n)
{
    // Calculating sum
    let sum = 0;
    for (let i = 0; i < n; i++)
        for (let j = 0; j < n; j++)
            sum += a[i][j];
       
    // Returning mean
    return sum / (n * n);
}
   
// Function for
// calculating variance
function variance(a, n, m)
{
    let sum = 0;
    for (let i = 0; i < n; i++)
    {
        for (let j = 0; j < n; j++)
        {
   
            // subtracting mean
            // from elements
            a[i][j] -= m;
   
            // a[i][j] = fabs(a[i][j]);
            // squaring each terms
            a[i][j] *= a[i][j];
        }
    }
   
    // taking sum
    for (let i = 0; i < n; i++)
        for (let j = 0; j < n; j++)
            sum += a[i][j];
   
    return sum / (n * n);
}
 
// Driver code
 
// declaring and
// initializing matrix
let mat = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]];
   
// for mean
let m = mean(mat, 3);
   
// for variance
let varr = variance(mat, 3, m);
   
// for standard
// deviation
let dev = Math.sqrt(varr);
   
// displaying variance
// and deviation
document.write("Mean: " + Math.floor(m) + "<br/>");
document.write("Variance: " +
                            Math.floor(varr) + "<br/>");
document.write("Deviation: " +
                        Math.floor(dev) + "<br/>");
                             
// This code is contributed by code_hunt.                           
</script>
Output : 



Mean: 5
Variance: 6
Deviation: 2

 

This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :