开发者

in or out of a for loop in R - calculating the diagonal product of a matrix

I'm trying to find the maximum diagonal product of 2 digit numbers in开发者_C百科 a 20x20 matrix.

This gives an error message :

i <- 17:1
z <- for (j in 1:(18-i))
        {b <- max ((x[i,j]*x[i+1,j+1]*x[i+2,j+2]*x[i+3,j+3]))}}

But this doesn't:

z <- for (i <- 17:1)
{for (j in 1:(18-i))
        {b <- max ((x[i,j]*x[i+1,j+1]*x[i+2,j+2]*x[i+3,j+3]))}}

but the second version gives me a number too small . Why does the first one not work, i think it would yield the correct answer, but i don't understand the error message.


This looks wrong.

You cannot assign the result of a for loop to a variable. And max() is over a scalar variable which is nonsense. Lastly, matrix x isn't specified. I'd retry with something smaller, and maybe even print some interim results to screen.

Walk before you run is still good advice. Later you can still vectorise for a sprint solution.


Actually, contrary to Dirk I believe that you should be aware of vectorization in R as soon as possible. The loop structure you try to implement is far from optimal, and actually redundant. Using a for-loop should be done only in very specific cases. Check the discusison in this question. Take a look at the help files of convenience functions like diag(), combn(), prod() and apply().

It's easy to combine them to do what you want :

x <-matrix(1:400,ncol=20)

Diag <- diag(x)

Id <- combn(1:length(Diag),2)

Diag.prod <- apply(matrix(Diag[Id],ncol=2),1,prod)

Max.Diag.prod <- max(Diag.prod)

Edit : You use a data frame, but you can use as.matrix(x) to convert this easily to a matrix.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜