Skip to content

Applying a function to each element of an array

8 messages · Tim Smith, Bert Gunter, Kjetil Holuerson +3 more

#
Well, since Sum(i=1 to i-n) =n*(n+1)/2, your loop simply gives
1/4*count*(count-1).
So if your matrix is A, A*(A-1)/4 is about the quickest way to get your
answer I think.

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box
#
Tim Smith wrote:
This is not a function!  Maybe you want

helper <- function(count) sum(0.5^((1:count)-1))
mapply(helper, yourmat)

gives you the elements of the matrix, as a vector. So you only must 
reassemble as a matrix:

n <- nrow(yourmat)
p <- ncol(yourmat)
matrix( mapply(helper, yourmat), n, p)

Kjetil
--
#
If A is the matrix the answer is 2*(1 - 2^(-A)), which took about 10secs 
for an example of your size.

        
On Fri, 7 Oct 2005, Tim Smith wrote:

            

  
    
#
On Fri, 7 Oct 2005, Prof Brian Ripley wrote:

            
NB: I have assumed n >= 1 here, as people nornally do when using 1:count.

  
    
#
If there weren't an analytic solution to your problem,
then you could build a vector of the answers from 1
to the maximum in the matrix.  Call that 'wtvec'.  Then:

ans <- array(NA, dim(A), dimnames(A))
ans[] <- wtvec[as.vector(A)]

should get you what you want.


Patrick Burns
patrick at burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")
Tim Smith wrote:

            
#
On Fri, 7 Oct 2005, Patrick Burns wrote:

            
Well, we don't actually know 'count' is >= 1.  I almost suggested this, 
but suppose the counts were in billions?

It's a good solution for a small set of continguous values.  If there is a 
small set of values, do a two-step lookup using e.g. match to find the 
enumeration of the values.
#
The sum in the loop is simply:  2 - (0.5)^count.  

So you don't need this loop.  As "count" gets large, the sum approaches 2.

Ravi.