Data: mat2.txt
/*
行列の分散,共分散を計算するプログラム

 1  2  2
 0 -2 -1
 2  1  3
 1  3  2
-2  4  1
*/
#include 
#include 
#define NDATA 5
#define K 3
void inputdata(FILE *fdata,double x[][K],int m, int n);
void devcalc(double w[][K],double wdev[][K],int m,int n);
void matprod(double x[][NDATA],double y[][K],double z[][K],int m,int k,int n);
void mattrans(double x[][K],double y[][NDATA],int m,int n);
void out_res(double a[][K],int m,int n);

main()
{
 double w[NDATA][K],wdev[NDATA][K],wdevt[K][NDATA],wprod[K][K],s[K][K],r[K][K];
 int i,j;
 FILE *fdata;
 fdata=fopen("mat2.txt","r");
 inputdata(fdata,w,NDATA,K);
 devcalc(w,wdev,NDATA,K);
 mattrans(wdev,wdevt,NDATA,K);
 matprod(wdevt,wdev,wprod,K,NDATA,K);
 for(i=0;i<=K-1;i++)
   for(j=0;j<=K-1;j++){
     s[i][j]=wprod[i][j]/(NDATA-1);
     r[i][j]=wprod[i][j]/sqrt(wprod[i][i]*wprod[j][j]);}
 printf("Variances and Covariances \n");
 out_res(s,K,K);
 printf("Correlation Coefficients \n");
 out_res(r,K,K);
 fclose(fdata);
}

void inputdata(FILE *fdata,double x[][K],int m,int n)
{
 int i,j;
 double d;
 for(i=0;i<=m-1;i++)
   for(j=0;j<=n-1;j++){
     fscanf(fdata,"%lf",&d);
     x[i][j]=d;
     }
}

void devcalc(double w[][K],double wdev[][K],int m,int n)
{
 int i,j;
 double a;
 for(j=0;j<=n-1;j++){
   a=0;
   for(i=0;i<=m-1;i++)a=a+w[i][j];
   a=a/m;
   for(i=0;i<=m-1;i++)wdev[i][j]=w[i][j]-a;
   }
}

void matprod(double x[][NDATA],double y[][K],double z[][K],int m,int k,int n)
{
 int i,j,r;
 double a;
 for(i=0;i<=m-1;i++)
   for(j=0;j<=n-1;j++){
       a=0;
       for(r=0;r<=k-1;r++)a=a+x[i][r]*y[r][j];
       z[i][j]=a;
     }
}

void mattrans(double x[][K],double y[][NDATA],int m,int n)
{
 int i,j;
 for(i=0;i<=m-1;i++)
   for(j=0;j<=n-1;j++)
     y[j][i]=x[i][j];
}

void out_res(double x[][K],int m,int n)
{
 int i,j;
 for(i=0;i<=m-1;i++){
   for(j=0;j<=n-1;j++)printf("%10.4f",x[i][j]);
   printf("\n");
   }
}


[出力結果]

Variances and Covariances 
    2.3000   -1.0500    1.3000
   -1.0500    5.3000    1.9500
    1.3000    1.9500    2.3000
Correlation Coefficients 
    1.0000   -0.3007    0.5652
   -0.3007    1.0000    0.5585
    0.5652    0.5585    1.0000


Back to C Language

Google




BLOG
PICASAWEB
Panoramio


REF:


Cによる統計データ解析入門