Skip to content

Outer product from matrix by row and a vector

6 messages · Ingo Reinhold, David Winsemius, Jeff Newmiller +1 more

#
On Aug 7, 2012, at 9:02 PM, Ingo Reinhold wrote:

            
(You really should not be referring to a and b inside that function  
body. It's arguments are now named x and y.)

Can you tell us what the answer _should_ be for the first entry? And a  
step by step illustration of how you got there?

If this is not what it should be, then you need to read up on the  
expected result of the division of a scalar by a vector in R.

  apply(a, 1, function(x) { x[1] + x[3]/ b } )

          [,1] [,2]
[1,] 6.000000  8.0
[2,] 3.500000  5.0
[3,] 2.666667  4.0
[4,] 2.250000  3.5
Do "this" is still somewhat nebulous.
David Winsemius, MD
Alameda, CA, USA
#
Can you post what you want your answer to be for the a and b you have given already?
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.
Ingo Reinhold <ingor at kth.se> wrote:

            
#
Hi Jeff, David, 

what I'm trying to do is speed the currently used nest for loop

a<-matrix(c(1:6),ncol=3)
b<-c(1,2,3,4)

result<-matrix(rep(0, times=dim(a)[1]*length(b)),nrow=dim(a)[1])
for(ii in 1:dim(a)[1]){
  for(jj in 1:length(b)){
    result[ii,jj]<-a[ii,1]+a[ii,3]/b[jj]
      }
}

giving the result

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

Thanks for taking a look. 

Cheers, 

Ingo
#
On Wed, Aug 08, 2012 at 06:03:19AM +0000, Ingo Reinhold wrote:
Hi.

The printed matrix is "a". The above code yields on my computer

       [,1] [,2]     [,3] [,4]
  [1,]    6  3.5 2.666667 2.25
  [2,]    8  5.0 4.000000 3.50

Try the following

  out <- a[, 1] + a[, 3] %o% (1/b)

  max(abs(out - result))

  [1] 4.440892e-16

Hope this helps.

Petr Savicky.
#
On Aug 7, 2012, at 11:26 PM, Petr Savicky wrote:

            
That is not what result equals (as Petr illustrates.)
It's also the case that the printed result is just the transpose of  
what I earlier offered as a possible implementation of the OP's pseudo- 
code.:

 > identical( t( apply(a, 1, function(x) { x[1] + x[3]/ b } ) ), result)
[1] TRUE