-2

I have a sample matrix like

 5 4 3  
 2 6 8   
 1 9 7   

and I want output like

max(5*6,5*8,5*9,5*7)  // i!=j condition  
max(4*2,4*8,4*1,4*7)  
max(3*2,3*6,3*1,3*9)  

And so on...

This maximum values obtained after computation should be in matrix form. I need to generalize it, therefore I need a generic code.

Molx
  • 6,816
  • 2
  • 31
  • 47
Saurabh Kumar
  • 149
  • 12
  • 5
    You should be able to solve this with `for` loops yourself. Demonstrate some effort in your question. – Roland Jul 01 '15 at 20:37
  • This code is giving the maximum value obtained for first row, I want the same operation on all rows provided the condition of "i not equal to j" remains same on all rows – Saurabh Kumar Jul 01 '15 at 20:38

1 Answers1

2

This gets the job done but is a pretty unimaginative solution, in that it just loops through the rows and columns performing the requested calculation instead of doing anything vectorized.

sapply(1:ncol(m), function(j) sapply(1:nrow(m), function(i) max(m[i,j]*m[-i,-j])))
#      [,1] [,2] [,3]
# [1,]   45   32   27
# [2,]   18   42   72
# [3,]    8   72   42

Data:

(m <- matrix(c(5, 2, 1, 4, 6, 9, 3, 8, 7), nrow=3))
#      [,1] [,2] [,3]
# [1,]    5    4    3
# [2,]    2    6    8
# [3,]    1    9    7
josliber
  • 43,891
  • 12
  • 98
  • 133
  • For nonnegative numbers, it should be faster to factor out the multiplication: `m[i,j]*max(m[-i,-j])` No idea if that's the scope of the OP's application, though. – Frank Jul 01 '15 at 20:43
  • @Frank I just moved the `max` outside the multiplication to address SvenHohenstein's comment that my previous solution (which is exactly what you're describing) only worked for non-negative matrices. We can't have it both ways, I'm afraid. Then again, I would imagine the efficiency hit you're describing is quite small. – josliber Jul 01 '15 at 20:46
  • Oh ok. I didn't notice your first iteration of the answer. Yeah, as the size scales up, the `max` should dominate the cost, I guess. – Frank Jul 01 '15 at 20:49
  • 2
    Another version with `outer` `outer(1:nrow(m1), 1:ncol(m1), FUN= Vectorize(function(i,j) max(m1[i,j]*m1[-i,-j])))` – akrun Jul 01 '15 at 20:51