tags:

views:

86

answers:

2

I'm trying to find the maximum diagonal product of 2 digit numbers in 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.

+6  A: 

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.

Dirk Eddelbuettel
wouldn't b be a vector from which max would give the maximum value?
Also, to get the data, i used read.table("filename") so i'm not exactly sure if it's in matrix form or whatever a table is.
ok, it's a data frame -- is it harder to work with data frames or matrices?
I think you mean you __can't__ assign the result of a for loop to a variable (in recent versions of R, anyway)
hadley
Thanks, Hadley. One day I will learn to proof-read. Now fixed.
Dirk Eddelbuettel
+1  A: 

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.

Joris Meys