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

I have an nx1 column vector, each element e_n an integer between 1 and p.  I want to convert it to an nxp matrix with a 1 as the e_nth element of each row and the rest 0.

 

have = {6,9,1,...}

 

want = {0 0 0 0 0 1 0 0 0  ... ,

             0 0 0 0 0 0 0 0 1 ... ,

             1 0 0 0 0 0 0 0 0 ... ,

              ...                             }

 

What's the easiest way to do that?

1 ACCEPTED SOLUTION

Accepted Solutions
Rick_SAS
SAS Super FREQ

The easiest way is to use the SUB2NDX function to convert (row,col) subscripts into indices.  You didn't specify the dimensions of the final matrix, so in the following example I used a 10-column matrix. You can modify the dimension as you need to:

 

proc iml;
have = {6,9,1,2};
/* Somewhere you need to specify the columns of want? 
   Is it max(have)? Is is square? */
want = j(nrow(have),10,0);
rows = T(1:nrow(have));
idx = sub2ndx(dimension(want), rows||have);
want[idx] = 1;
print want; 

View solution in original post

3 REPLIES 3
Rick_SAS
SAS Super FREQ

The easiest way is to use the SUB2NDX function to convert (row,col) subscripts into indices.  You didn't specify the dimensions of the final matrix, so in the following example I used a 10-column matrix. You can modify the dimension as you need to:

 

proc iml;
have = {6,9,1,2};
/* Somewhere you need to specify the columns of want? 
   Is it max(have)? Is is square? */
want = j(nrow(have),10,0);
rows = T(1:nrow(have));
idx = sub2ndx(dimension(want), rows||have);
want[idx] = 1;
print want; 
IanWakeling
Barite | Level 11

Or how about the 'unique design' trick?

 

proc iml;

have = {6, 9, 1, 6, 2};

want = j( nrow(have), max(have), 0);
want[ , unique(have)] = design(have);

print want;
Ksharp
Super User
Or use this simple way to get index you need.


proc iml;
have = {6,9,1,2};
want = j(nrow(have),max(have),0);
idx = t(have)+(0:nrow(have)-1)#max(have);
want[idx] = 1;
print want; 
quit;

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

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
  • 3 replies
  • 1043 views
  • 3 likes
  • 4 in conversation