For the example of the function you gave, it is already 'vectorized':
myfunc - function(x1, x2) {
+ x1 + x2
+ }
myfunc(1:10, 1:10)
[1] 2 4 6 8 10 12 14 16 18 20
outer(1:10, 1:10, myfunc)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]2345678
Hi All,
I want to do something along the lines of:
for (i in 1:n){
for (j in 1:n){
A[i,j]-myfunc(x[i], x[j])
}
}
The question is what would be the most efficient way of doing this. Would
using functions such as sapply be more efficient that using a for loop?
Note that n can be a
Take a look at 'outer' and vectorized your function. Also look at
'expand.grid'.
On Sunday, November 27, 2011, Sachinthaka Abeywardana
sachin.abeyward...@gmail.com wrote:
Hi All,
I want to do something along the lines of:
for (i in 1:n){
for (j in 1:n){
A[i,j]-myfunc(x[i],
Hi Sachin,
The technique you are suggesting is likely to be just as efficient as
any other if indeed myfunc must be called on each x[i] x[j] element
individually. I would take the additional steps of instantiating A as
a matrix (something like:
A - matrix(0, nrow = n, ncol = n)
Depending, you
Hi Jim,
What exactly do you mean by vectorized. I think outer looks like what I was
looking for. BUT there was a (weighted) distance matrix calculation that I
was trying to vectorize, which wasnt related to this post. Could you proved
a bit more details as to what you were referring to, and maybe
Here is an example, of course, this is predicated on how myfunc()
behaves---if it could not handle adding a constant to a vector, things
would choke:
## Current method
myfunc - function(x1, x2) {
x1 + x2
}
x - 1:10
n - length(x)
A - matrix(0, nrow = n, ncol = n)
for (i in 1:n){
for (j in
6 matches
Mail list logo