mrkb80
mrkb80

Reputation: 591

Apply indexed function to each value in row of matrix

I want to apply the function exp(-r*(i/500)) to every value in the row of a matrix (where i represents the column number). I know how to do this with a loop, but I'm trying to learn the "correct" method in R.

I thought about:

apply(st,1,function(v) { exp(-r * (i/500)*v })

but I don't know how to define the value i, such that it will increment for each column.

I know a loop will accomplish this, but I am fairly certain that is not the optimal method in R.

Upvotes: 3

Views: 301

Answers (3)

IRTFM
IRTFM

Reputation: 263352

Try this, since col(st) will return a matrix of the same dimensions as st populated with the columns

st* exp(-r * (col(st)/500))

Not surprisingly there is also a row function and together they can be useful. A multiplication table:

m <- matrix(NA, 12,12)
m=col(m)*row(m)

Upvotes: 3

Arun
Arun

Reputation: 118799

If you have to use apply, then something like this?

> apply(as.matrix(seq_len(ncol(m))), 1, function(x) exp(-r * m[,x]/500))

Where m is your matrix.

Of course, there is no need to use apply here. You just need to construct an appropriate matrix.

exp(-r * matrix(rep(1:ncol(m), nrow(m)), nrow=nrow(m), byrow=T)/500) * m

Upvotes: 3

juba
juba

Reputation: 49033

Maybe something like this ?

## m is the matrix with your data
m <- matrix(1:50,ncol=10,nrow=5)
## m2 is a matrix with same dimensions and each element is the column number
m2 <- matrix(rep(1:ncol(m),nrow(m)),ncol=ncol(m),nrow=nrow(m),byrow=TRUE)
## Compute m2 such as each value is equal to expr(-r*(i/500))
m2 <- exp(-r*(m2/500))
## multiply m and m2
m*m2

Upvotes: 1

Related Questions