Hi:
x <- matrix(20:35, ncol = 1)
u <- c(1, 4, 5, 6, 11) # 'x values'
m <- c(1, 3, 1, 1, 0.5)
# Function to compute the inner product of the multipliers with the
extracted
# elements of x determined by u
f <- function(mat, inputs, mults) crossprod(mat[inputs], mults)
f(x, u, mults = c(1, 3, 1, 1, 0.5))
[,1]
[1,] 153
20 + 23 * 3 + 24 + 25 + 30 * 0.5
[1] 153
The function is flexible enough to allow you to play with the input
matrix
(although a vector would also work), the 'observation vector' inputs
and the
set of multipliers. Here's one way (not necessarily the most
efficient):
uv <- matrix(sample(1:15, 25, replace = TRUE), ncol = 5)
uv # like an X matrix, where each row provides the input values of
the
vars
[,1] [,2] [,3] [,4] [,5]
[1,] 12 8 11 10 15
[2,] 15 11 14 14 8
[3,] 4 8 4 10 12
[4,] 10 5 2 1 7
[5,] 11 4 9 1 11
# Apply the function f to each row of uv:
apply(uv, 1, function(y) f(x, y, mults = c(1, 3, 1, 1, 0.5)))
[1] 188.0 203.5 171.5 155.0 162.0
The direct matrix version:
crossprod(t(matrix(x[uv], ncol = 5)), c(1, 3, 1, 1, 0.5))
[,1]
[1,] 188.0
[2,] 203.5
[3,] 171.5
[4,] 155.0
[5,] 162.0
Notice that the apply() call returns a vector whereas crossprod()
returns a
matrix.
x[uv] selects the x values associated with the indices in uv and
returns a
vector in column-major order. The crossprod() call transposes the
reshaped
x[uv] and then 'matrix' multiplies it by the vector c(1, 3, 1, 1,
0.5).
HTH,
Dennis
On Fri, Oct 29, 2010 at 3:54 PM, M.Ribeiro
<mresendeufv at yahoo.com.br> wrote: