/* Homework 3 problem 1 * Given 3 2D vectors * Covariance matrix and its eigenvalues are calculated */ #include #include int main( int argc, char** argv ) { // a, b, c are the user input vectors float a[2]; float b[2]; float c[2]; // Covariance Matrix float cov[2][2]={0,0,0,0}; float avg[2]; float eigen[2]; // Prompt user to enter vectors printf("Please enter a[0]\n"); scanf("%f",&a[0]); printf("Please enter a[1]\n"); scanf("%f",&a[1]); printf("Please enter b[0]\n"); scanf("%f",&b[0]); printf("Please enter b[1]\n"); scanf("%f",&b[1]); printf("Please enter c[0]\n"); scanf("%f",&c[0]); printf("Please enter c[1]\n"); scanf("%f",&c[1]); // Show user what was entered printf("a[0]=%f a[1]=%f\n",a[0],a[1]); printf("b[0]=%f b[1]=%f\n",b[0],b[1]); printf("c[0]=%f c[1]=%f\n",c[0],c[1]); int i,j; // holly counter duo for(i=0; i<2; i++){ avg[i] = (a[i] + b[i] + c[i])/3; } for(i=0; i<2; i++){ a[i] = (a[i] - avg[i]); } for(i=0; i<2; i++){ b[i] = (b[i] - avg[i]); } for(i=0; i<2; i++){ c[i] = (c[i] - avg[i]); } for(i=0; i<2; i++){ for(j=0; j<2; j++){ cov[i][j] += a[i]*a[j]; } } for(i=0; i<2; i++){ for(j=0; j<2; j++){ cov[i][j] += b[i]*b[j]; } } for(i=0; i<2; i++){ for(j=0; j<2; j++){ cov[i][j] += c[i]*c[j]; } } for(i=0; i<2; i++){ for(j=0; j<2; j++){ cov[i][j] = (cov[i][j]/2); } } printf("Covariance matrix is:\n"); for(i=0; i<2; i++){ for(j=0; j<2; j++){ printf("%f\t",cov[i][j]); } printf("\n"); } // visit http://en.wikipedia.org/wiki/Eigenvalue_algorithm to see how eigenvalues for 2x2 matrices are found eigen[0] = (cov[0][0]+cov[1][1])/2 - sqrt(4*cov[0][1]*cov[1][0]+((cov[0][0]-cov[1][1])*(cov[0][0]-cov[1][1]))) /2; eigen[1] = (cov[0][0]+cov[1][1])/2 + sqrt(4*cov[0][1]*cov[1][0]+((cov[0][0]-cov[1][1])*(cov[0][0]-cov[1][1]))) /2; for(i=0; i<2; i++){ printf("eigenvalue %d is %f\n",i,eigen[i]); } exit( 0 ); }