Affine
Affine

Reputation: 35

Create matrix with elements returned by a function

I have two vectors x and y with some values and I need to generate the matrix which elements would be returned by a function f(x,y) applied to those 2 vectors. That is the matrix M will have a typical element

M[i,j] <- f(x[i], y[j])

What is the most efficent way to do this if I want to avoid loops? I can generate matrix columns or rows by using sapply function, i.e.

M[i, ] <- sapply(y, f, x = x[i])

But I still need to apply loop in other dimension which is very slow, because the dimension of x is huge. Is it possible to use apply family of function and avoid loops completely?

Upvotes: 2

Views: 2041

Answers (1)

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32401

That is exactly what the outer function does:

outer(x, y, f)

If f is not vectorized, you need:

outer(x, y, Vectorize(f))

Upvotes: 5

Related Questions