BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Kona
Fluorite | Level 6

Hi,

I am struggling with how to speed up the following program. I have been trying to vectorize things, however, cannot get things to work. In the example below I have a 5x5 matrix, however, in practice the matrix is much larger, e.g., 5000 x 5000. Thanks so much for any help or suggestions.

-Michael

 

proc IML;
nP=5;
CM= {0 0.5 0.75 0 0.75 , 1 0 1 0 0.5 , 0.375 0.25 0 0.375 0.25 , 0 0 1 0 0, 1 0.333 0.667 0 0 };
print CM;
 
D = j(nP,nP,0);
  do i1 = 1 to nP;
    do i2 = i1+1 to nP; /* I only need to do the calculation on one half of the CM matrix as the resulting D matrix is symmetric */
      do k=1 to nP;
        if k ^= i1 && k ^= i2 then do; /* I don't use the cases when i1=i2 or i2=i1 */
            D[i1,i2] = D[i1,i2] + (CM[i1,k] - CM[i2,k])**2 + (CM[k,i1] - CM[k,i2])**2;
        end;
      end;
     D[i1,i2] = sqrt(D[i1,i2]);
     D[i2,i1] = D[i1,i2]; 
  end;
 end;
print D;
end;
quit;
run;
1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User

proc IML;
nP=5;
CM= {0 0.5 0.75 0 0.75 , 1 0 1 0 0.5 , 0.375 0.25 0 0.375 0.25 , 0 0 1 0 0, 1 0.333 0.667 0 0 };
print CM;
 
D = j(nP,nP,0);
  do i1 = 1 to nP;
    do i2 = i1+1 to nP; 
	  temp=(CM[i1,]-CM[i2,])##2 + t((CM[,i1]-CM[,i2])##2);
	  temp[i1||i2]=0;/* I don't use the cases when i1=i2 or i2=i1 */
      D[i1,i2] = sqrt(cusum(temp)[nP]);
  end;
 end;
D=D`+D;
print D;
quit;

View solution in original post

2 REPLIES 2
Ksharp
Super User

proc IML;
nP=5;
CM= {0 0.5 0.75 0 0.75 , 1 0 1 0 0.5 , 0.375 0.25 0 0.375 0.25 , 0 0 1 0 0, 1 0.333 0.667 0 0 };
print CM;
 
D = j(nP,nP,0);
  do i1 = 1 to nP;
    do i2 = i1+1 to nP; 
	  temp=(CM[i1,]-CM[i2,])##2 + t((CM[,i1]-CM[,i2])##2);
	  temp[i1||i2]=0;/* I don't use the cases when i1=i2 or i2=i1 */
      D[i1,i2] = sqrt(cusum(temp)[nP]);
  end;
 end;
D=D`+D;
print D;
quit;

Kona
Fluorite | Level 6

Many thanks Ksharp. That was exactly what I was looking for.

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

From The DO Loop
Want more? Visit our blog for more articles like these.
Discussion stats
  • 2 replies
  • 1594 views
  • 2 likes
  • 2 in conversation