1

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.

Joris Meys
  • 106,551
  • 31
  • 221
  • 263
Thomas
  • 847
  • 4
  • 12
  • 21

2 Answers2

6

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
  • 360,940
  • 56
  • 644
  • 725
1

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.

Community
  • 1
  • 1
Joris Meys
  • 106,551
  • 31
  • 221
  • 263