Statistical programming, matrix languages, and more

Re-order matrix based on another index matrix.

Posts: 37

Re-order matrix based on another index matrix.

Hi, there:

I wonder how I should do it with SAS/IML.

Imagine x is a m*1 vector and I want to pick up some values from the specified positions defined by another vector, idx. For example, idx={ 2,3,7,5,10,2,7}.  I write a line as:


zz is supposed to be a 7*1 vector whose values are from the values in corresponding positions in x, according to the index vector idx_k.

Unfortunately, the last line does not seem to be consistent with SAS/IML grammar. If we want to re-order a matrix based on an index defined by another matrix, how should we do it? 

I do find some example related to my question, but I find it difficult to interpret:

In a sample code on how to use the rank function:

x={2 2 1 0 5};  /*value x

b=x;               /*value b from x


It is difficult to understand the last line. does it revalue x? If so, can just write z[,rank(x)]=b, while z is undefined matrix or a 1*m matrix with m>=5 or can I write x[,rank(x)]=x?


Posts: 4,242

Re-order matrix based on another index matrix.

Posted in reply to bigbigben

I think you can use the ideas in this blog post:

The post uses the SORTNDX function, which is explained further in this post:

In your example, IDX is not a valid index into X because IDX contains the value 10. The expression x[10] does not make sense because X has fewer than 10 elements. If you define r=rank(idx), then zz=x[r,] is defined.

Ranks and sorts can be confusing because sometimes you need to use the rank and sometimes you need to use the anti-rank.

Ask a Question
Discussion stats
  • 1 reply
  • 2 in conversation