BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
IanWakeling
Barite | Level 11

I developed my idea above into a small helper function that others might find useful.

 

proc iml;
  /* The TRI_IDX function returns the index numbers of the triangular elements in a
     square matrix of side n.

       The parameter UPPER is a Boolean that gives the upper triangle when true,
       the lower triangle when false. 

       The parameter MAINDIAG is a Boolean that indicates whether or not the
       elements from the main diagonal should be included.
  */
  start tri_idx(n, upper, maindiag);
	idx = cusum( vech( diag((1-maindiag):(n-1)) + 1));
	if upper then return(idx); else return((n#n+1) - idx[nrow(idx):1] );
  finish;

  /* demonstrate function for a 4x4 matrix */
  print (shape(1:16,4)) [format=2.0];
  print (tri_idx(4,0,0)) [l='lower triangle no diagonal'];
  print (tri_idx(4,0,1)) [l='lower triangle including diagonal'];
  print (tri_idx(4,1,0)) [l='upper triangle no diagonal'];
  print (tri_idx(4,1,1)) [l='upper triangle including diagonal'];
quit;
Rick_SAS
SAS Super FREQ

For additional thoughts on @IanWakeling's function, see "Extract the lower triangular elements of a matrix", which uses the built-in VECH function when the diagonal elements are included.

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
Multiple Linear Regression in SAS

Learn how to run multiple linear regression models with and without interactions, presented by SAS user Alex Chaplin.

Find more tutorials on the SAS Users YouTube channel.

From The DO Loop
Want more? Visit our blog for more articles like these.
Discussion stats
  • 19 replies
  • 3676 views
  • 18 likes
  • 6 in conversation