2012-10-19 7 views
0

안녕하세요 저는 텍스트 파일에서 레코드 사이의 거리를 찾으려고합니다. 나는 awk를 사용하여 그것을하려고 노력하고있다. 예시 입력된다 :awk 사이의 거리

1 2 1 4 yes 
2 3 2 2 no 
1 1 1 5 yes 
4 2 4 0 no 
5 1 0 1 no 

난 수치의 각각 사이의 거리를 찾을. 저는 값을 빼고 답을 제곱함으로써 이것을합니다. 내가 아래의 코드를 시도했지만 모든 거리는 단순히 0입니다. 어떤 도움을 주시면 감사하겠습니다.

BEGIN {recs = 0; fieldnum = 5;} 
{ 
    recs++; 
    for(i=1;i<=NF;i++) {data[recs,i] = $i;} 
} 
END { 
    for(r=1;r<=recs;r++) { 
    for(f=1;f<fieldnum;f++) { 
     ##find distances 
     for(t=1;t<=recs;t++) { 
     distance[r,t]+=((data[r,f] - data[t,f])*(data[r,f] - data[t,f])); 
      } 
     } 
    } 
     for(r=1;r<=recs;r++) { 
     for(t=1;t<recs;t++) { 
     ##print distances 
     printf("distance between %d and %d is %d \n",r,t,distance[r,t]); 
     } 
     } 
    } 
+3

일부 출력과 _define_ 거리를 포함하십시오. – Steve

답변

3

는 "숫자 값의 각 사이의 거리"에 의해 개념적으로 무엇을 의미하는지 아무 생각이 그래서 알고리즘에 도움이 없지만 이제 그 모습을 볼 수있는 코드를 정리 할 수 ​​없습니다

$ cat tst.awk 
{ 
    for(i=1;i<=NF;i++) { 
     data[NR,i] = $i 
    } 
} 
END { 
    for(r=1;r<=NR;r++) { 
    for(f=1;f<NF;f++) { 
     ##find distances 
     for(t=1;t<=NR;t++) { 
      delta = data[r,f] - data[t,f] 
      distance[r,t]+=(delta * delta) 
     } 
    } 
    } 
    for(r=1;r<=NR;r++) { 
    for(t=1;t<NR;t++) { 
     ##print distances 
     printf "distance between %d and %d is %d\n",r,t,distance[r,t] 
    } 
    } 
} 
$ 
$ awk -f tst.awk file 
distance between 1 and 1 is 0 
distance between 1 and 2 is 7 
distance between 1 and 3 is 2 
distance between 1 and 4 is 34 
distance between 2 and 1 is 7 
distance between 2 and 2 is 0 
distance between 2 and 3 is 15 
distance between 2 and 4 is 13 
distance between 3 and 1 is 2 
distance between 3 and 2 is 15 
distance between 3 and 3 is 0 
distance between 3 and 4 is 44 
distance between 4 and 1 is 34 
distance between 4 and 2 is 13 
distance between 4 and 3 is 44 
distance between 4 and 4 is 0 
distance between 5 and 1 is 27 
distance between 5 and 2 is 18 
distance between 5 and 3 is 33 
distance between 5 and 4 is 19 

출력이 0이 아닌 것 같습니다.