Skip to content

Index of item in matrix

8 messages · John Janmaat, Marc Schwartz, Ott Toomet +4 more

#
Hello All,

Is there a fast way to find the index(row and column) of a point in a 
matrix?

Thanks,

John.
#
Look at ?which.

Specifically the form: which(x, arr.ind = TRUE)
[,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
row col
[1,]   3   3
[1] 9


HTH,

Marc Schwartz
#
Satisfying what conditions?

Does the following example help you get what you want?

 > set.seed(1)
 > A <- array(rnorm(12), dim=c(3,4))
 >
 > sel <- (round(A)==1)
 > sel
       [,1]  [,2]  [,3]  [,4]
[1,] FALSE FALSE FALSE  TRUE
[2,] FALSE  TRUE FALSE FALSE
[3,] FALSE FALSE FALSE FALSE
 > cbind(row(A)[sel],col(A)[sel])
      [,1] [,2]
[1,]    2    2
[2,]    1    4

Spencer Graves
John Janmaat wrote:
#
Hi,

 | Date: Wed, 02 Apr 2003 14:39:05 -0400
 | From: John Janmaat <john.janmaat at acadiau.ca>
 | Hello All,
 | 
 | Is there a fast way to find the index(row and column) of a point in a 
 | matrix?

what do you mean as ,,a point in a matrix''?  Perhaps 
which( ,arr.ind=T) does what you are looking for.

Best wishes,
Ott
#
On Wed, 2 Apr 2003, John Janmaat wrote:

            
row col
[1,]   1   1
[2,]   2   1
[3,]   2   2
[4,]   5   2
[5,]   1   3
[6,]   2   4
#
R> a <- matrix(1:25, ncol=5)
R> which(a == 2, arr.ind=TRUE)
     row col
[1,]   2   1
R> a
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25

best,

Torsten
#
Or more simply:

 > set.seed(1)
 > A <- array(rnorm(12), dim=c(3,4))
 > which(round(A) == 1, arr.ind = TRUE)
      row col
[1,]   2   2
[2,]   1   4

Though, the original post may need more clarification.

Sundar
Spencer Graves wrote:
#
Sundar's solution is better than mine unless the code must also work in 
S-Plus.

Spencer Graves
Sundar Dorai-Raj wrote: