Math
Math

Reputation: 1294

Distance function for sas 9.2

In SAS 9.3 we can easily calculate the Euclidean distance matrix between lat, lon by using function distance

proc iml;
n=5; 
seed=123456789;
    lat= J(n,1,0); lon= J(n,1,0);
    i = 1;  do while (i <= n); 
    lat[i] = uniform(seed);                                                                                                  
    lon[i] = uniform(seed);                                                                                                  
     i = i + 1;  end;
mat=lat||lon;
dist=distance(mat); 
run;
quit; 

I can't find this function in SAS 9.2 How can I do it in 9.2 ?

Thank you.

Upvotes: 2

Views: 300

Answers (2)

Math
Math

Reputation: 1294

Thanks to @Joe, I can use the answer of Rick Wicklin in proc iml as :

proc iml;
n=5; 
seed=123456789;
    lat= J(n,1,0); lon= J(n,1,0);
    i = 1;  do while (i <= n); 
    lat[i] = uniform(seed);                                                                                                  
    lon[i] = uniform(seed);                                                                                                  
     i = i + 1;  end;
mat=lat||lon;

start PairwiseDist(x, y);
if ncol(x)^=ncol(y) then return (.); /* Error */
p = nrow(x); q = nrow(y);
idx = T(repeat(1:p, q)); /* index matrix for x */
jdx = shape(repeat(1:q, p), p); /* index matrix for y */
diff = abs(X[idx,] - Y[jdx,]);
return( shape( sqrt(diff[,##]), p ) );
finish;
start EuclideanDistance(x); /* in place of 12.1 DISTANCE function */
y=x;
return( PairwiseDist(x,y) );
finish;
distance=EuclideanDistance(mat);
print distance;

run;
quit;

Thank you Joe and thaks to Rick Wicklin.

Upvotes: 1

Joe
Joe

Reputation: 63424

Rick Wicklin answers this question in a blog post, in which he introduces the distance function, but also tells you how to do it two other ways.

  • PROC DISTANCE (not an IML procedure, but produces a matrix-like dataset you could easily load into IML)
  • Write your own module. You need to create a pairwisedist() module that would define how to compute euclidian distance for a matrix. Essentially you determine the difference between all combinations of the rows in the matrix. Then sum the squares of the differences and take the square root.

An example of PROC DISTANCE:

proc iml;
n=5; 
seed=123456789;
    lat= J(n,1,0); lon= J(n,1,0);
    i = 1;  do while (i <= n); 
    lat[i] = uniform(seed);                                                                                                  
    lon[i] = uniform(seed);                                                                                                  
     i = i + 1;  end;


  mat=lat||lon;
  create matdata from mat [colname={'x1' 'x2' 'x3' 'x4' 'x5'}];
    append from mat;
  close matdata;
  quit;

proc distance data=matdata out=dist method=Euclid nostd;
  var interval(x1 x2);
run;

Upvotes: 4

Related Questions