0

I need to convert the iteration below into matrix operation.

a = certain_matrix(3,5)
mat = matrix(0, 3,3)

for ( i in 1:3 )
  for ( j in 1:3 )
    mat[i,j] = certain_distance(a[i,], a[j,])

Roughly I need to use apply(). However, I cannot get hold of the row index in

apply(a, 1, function(x) XXX)

So how to perform that operation fast?

SolessChong
  • 2,847
  • 6
  • 35
  • 61
  • What's `certain_matrix`? – Thomas Aug 07 '13 at 09:56
  • You problem seems to be a duplicate of [this question](http://stackoverflow.com/q/18080568/1412059) I answered recently. However, there are some packages offering highly optimized functions for many distance measures. – Roland Aug 07 '13 at 09:58
  • @Thomas it's some lines of codes. returns a double – SolessChong Aug 07 '13 at 10:09
  • Soless - a "double" is a scalar. Clearly `certain_matrix` is returning an **array** of doubles. Meanwhile, how about rewriting your `certain_distance` function so it calculates all values rather than just the distance between two specified rows? – Carl Witthoft Aug 07 '13 at 11:35
  • Try `mat – flodel Aug 07 '13 at 11:54
  • @flodel I don't think `outer` in combination with `Vectorize` (which basically is a call to `mapply`) is much better than the for loops. Using `combn` as demostrated in the question I linked to should do better. – Roland Aug 07 '13 at 15:46

0 Answers0