📄 covariance.java
字号:
/** * file: Covariance.java * * Last editted: Ryan Irwin * */// import necessary java libraries////These imports are not needed - Phil T. 6-23-03//import java.awt.*;//import java.applet.*;//import javax.swing.*;/** * Covariance as the name sggests computes the covariance matrix given * two random vectors i.e., the X = (x1, x2, x3 ...) and Y = (y1, y2, y3 ...) */public class Covariance { // ********************************************************************* // // declare class methods // // ********************************************************************* /** * The method normalizes the covariance matrix based on the the range of * the values within the covariance matrix * * @param M covariance matrix */ public void normalizeCovariance(double[][] M) { // declare local variables // double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; // obtain the minimum and maximum value from the covariance matrix // for(int i=0; i < M.length; i++) { for(int j=0; j < M.length; j++) { if (M[i][j] < min) { min = M[i][j]; } if (M[i][j] > max) { max = M[i][j]; } } } // normalize the covariance matrix // for(int i=0; i < M.length; i++) { for(int j=0; j < M.length; j++) { M[i][j] = (M[i][j] - min) / (max - min); } } } /** * computes the covariance matrix given two discrete random variables * * @param x random vector X = (x1, x2, x3 ...) * @param y random vector Y = (y1, y2, y3 ...) * * @return covariance matrix */ public double[][] computeCovariance(double[] x, double[] y) { // declare local variables // double sum11 = 0.0; double sum12 = 0.0; double sum21 = 0.0; double sum22 = 0.0; double sum1 = 0.0; double mean1 = 0.0; double sum2 = 0.0; double mean2 = 0.0; // declare the covariance matrix // double[][] cov = new double[2][2]; // compute the mean of the first random variable // for(int i = 0; i < x.length; i++) { sum1 += x[i]; } mean1 = sum1 / x.length; // compute the mean of the second random variable // for(int i = 0; i < y.length; i++) { sum2 += y[i]; } mean2 = sum2 / y.length; // compute the c11 component of the covariance matrix // for(int i = 0; i < x.length; i++) { sum11 += (x[i] - mean1) * (x[i] - mean1); } cov[0][0] = sum11 / (x.length - 1); // compute the c12 component of the covariance matrix // for(int i = 0; i < x.length; i++) { sum12 += (x[i] - mean1) * (y[i] - mean2); } cov[0][1] = sum12 / (x.length - 1); // compute the c21 component of the covariance matrix // for(int i = 0; i < x.length; i++) { sum21 += (y[i] - mean2) * (x[i] - mean1); } cov[1][0] = sum21 / (x.length - 1); // compute the c22 component of the covariance matrix // for(int i = 0; i < x.length; i++) { sum22 += (y[i] - mean2) * (y[i] - mean2); } cov[1][1] = sum22 / (x.length - 1); // return the covariance matrix // return cov; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -