How to Find the Variance of Numbers in 2D Array in C++?
Last Updated :
14 Feb, 2024
The variance of numbers is a measure of the spread of a set of values which is used to find how much the values in a dataset differ from mean or average. In this article, we will learn how to find the variance of numbers in a 2D array in C++.
Example
Input:
myMatrix = { { 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 } };
Output:
Variance: 666.667
Variance in a 2D Array in C++
To find the Variance in a 2D array we need to first calculate the mean i.e. the average of all the elements in a given 2D array:
The formula for Mean:
Then use that mean to find the variance (σ2) using the below formula for the set of n values (x₁, x₂,…, xₙ).
Formula for Variance:
C++ Program to Find the Variance in a 2D Array
The below example demonstrates how we can find a variance in a 2D array in C++.
C++
#include <cmath>
#include <iostream>
using namespace std;
double calculateVariance( int rows, int cols,
int matrix[][3])
{
double sum = 0;
double squaredDiff = 0;
int totalCount = rows * cols;
for ( int i = 0; i < rows; ++i) {
for ( int j = 0; j < cols; ++j) {
sum += matrix[i][j];
}
}
double overallMean = sum / totalCount;
for ( int i = 0; i < rows; ++i) {
for ( int j = 0; j < cols; ++j) {
squaredDiff
+= pow (matrix[i][j] - overallMean, 2);
}
}
double variance = squaredDiff / totalCount;
return variance;
}
int main()
{
const int rows = 3;
const int cols = 3;
int matrix[rows][cols] = { { 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 } };
double result = calculateVariance(rows, cols, matrix);
cout << "Variance: " << result << endl;
return 0;
}
|
Time Complexity: O(N * M), where N is the number of rows and M is the number of columns in the matrix.
Space Complexity: O(1)
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...