Reputation: 1
I have a square matrix, and I'm trying to:
I want to multiply each element of the matrix by row number element of the list, and olumn number element of the list.
Here's the matrix and the list from which I want my function to draw values to multiply for each matrix element.
states <- matrix(seq(1,9,1), nrow=3,ncol=3)
print(states)
rates <- seq(1, 5,2)
print(rates)
So for example, I want to multiply 8 in the matrix by 3*5 since it is in the 2nd row and 3rd column.
I've indexed the off-diagonal elements (not sure if this was the best way for my purposes):
delta <- row(states)-col(states)
And tried to sapply:
sapply(states[delta>0],function(i) {
i*rates[row(i)]*rates[col(i)]
print(states)
})
But I get the error message " Error in row(i) : a matrix-like object is required as argument to 'row' ". I know it's a problem with how I'm indexing the elements but can't think of a better way.
Thanks in advance!
Upvotes: 0
Views: 89
Reputation: 1
Figured out the answer!
The problem arose from trying to pick out a single value in the matrix, which doesn't work for functions row() and col().
So rather than indexing as
rates[row(i)]
it needed to be
rates[row(states)[i]]
Upvotes: 0