2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

c言語  分散、共分散関数

Posted at
sample.c
#include <stdio.h>
#include <math.h>

//共分散
double coefficient(double *x,double *y,int len){
    double avgx,avgy;
    double sumxy,sumxx,sumyy;
    int i;
    avgx=avgy=sumxx=sumyy=sumxy=0.0;
    for(i=0;i<len;++i){
        avgx+=x[i];
        avgy+=y[i];
    }
    
    avgx/=len;
    avgy/=len;
    for(i=0;i<len;++i){
        sumxy+=(x[i]-avgx)*(y[i]-avgy);
    }
    
    return sumxy/len;
}

//分散
double dispersion(double *x ,double len){
    double avgx=0,diff=0;
    double sumx=0,sumxx=0,powdiff[255];
    
    //平均
    for(int i=0;i<len;++i){
        sumx+=x[i];
    }
    
    avgx=sumx/len;
    
    //偏差ベクトル
    for(int i=0;i<len-1;++i){
        diff=avgx-x[i];
        powdiff[i]=pow(diff,2.0);
        sumxx+=powdiff[i];
    }
    
    return sumxx/len;
}

//試しにbook1.csvファイル(とある3地点の気圧)を読み込んで見る
int main(void){
    FILE *fp;
    char *fn = "book1.csv";//要書き換え
    int ret,count=0;
    double fpa[40],tpa[40],hpa[40],result[3][3];//なんでもいいです
    
    fp = fopen( fn, "r" );
    if( fp == NULL ){
        printf( "%sファイルが開けません¥n", fn );
        return -1;
    }
    
    while( ( ret = fscanf( fp,"%lf,%lf,%lf",&fpa[count],&tpa[count],&hpa[count]) ) != EOF ){
        count++;

    }
    fclose( fp );
    
 //共分散行列として2次元配列に格納   
    result[0][1]=result[1][0]=coefficient(fpa,tpa,count);
    result[0][2]=result[2][0]=coefficient(fpa,hpa,count);
    result[1][2]=result[2][1]=coefficient(tpa,hpa,count);

    result[0][0]=dispersion(fpa, count);
    result[1][1]=dispersion(tpa, count);
    result[2][2]=dispersion(hpa, count);
//共分散行列を出力
    for (int i=0; i<3; i++) {
        for (int f=0; f<3; f++) {
            printf("%lf  ",result[i][f]);
        }
        printf("\n");
    }
    
    return 0;
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?