# [R] Applying a function to a matrix using indexes as arguments

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Thu Dec 17 02:00:52 CET 2015

```Would

outer( A, B, `*` ) / C

do the trick for you?
--
Sent from my phone. Please excuse my brevity.

On December 16, 2015 4:41:13 PM PST, Matteo Richiardi <matteo.richiardi at gmail.com> wrote:
>My problem is of course more complicated, and is obviously not a
>homework.
>I just wanted to provide a minimal working example. You can replace the
>matrix C with a matrix containing any number, for what matters. Btw,
>because numbers are extracted from a Gaussian distribution, the
>likelihood
>that you draw a 0 is actually zero.
>
>Apart from this, apologies for having posted an html version.
>
>On 17 December 2015 at 00:36, Jeff Newmiller <jdnewmil at dcn.davis.ca.us>
>wrote:
>
>> This calculation divides by values centered around zero. The only
>context
>> that I can think of that would require such silliness is a homework
>> problem, and this list has a no-homework policy. If not, then
>mentioning
>> the theory you are applying might help someone point you at an
>existing
>> function that achieves your goals while avoiding divide-by-zero
>errors.
>>
>> Since you also posted in HTML I gather that you have not read the
>Posting
>> Guide mentioned below. Avoiding HTML on this list is to your benefit,
>since
>> using it inevitably leads to others seeing a garbled version of what
>you
>> --
>> Sent from my phone. Please excuse my brevity.
>>
>> On December 16, 2015 4:18:56 PM PST, Matteo Richiardi <
>> matteo.richiardi at gmail.com> wrote:
>>
>>> I have to evolve each element of a matrix W
>>>
>>> W <- matrix(0,2,3)
>>>
>>> according to some function which uses the indices of the matrix
>[i,j] as
>>> arguments:
>>> w.fun = function(i,j) {
>>>   return A[i]*B[j]/(C[i,j])
>>> }
>>>
>>> where
>>> A<-c(100,100)
>>> B<-c(200,200,200)
>>> C <- matrix( rnorm(6,mean=0,sd=1), 2, 3)
>>>
>>> How can I do it, without recurring to a loop? Also, in my
>application I
>>> need to pass the function another argument.
>>>
>>> Thanks a lot for your suggestions.
>>> Matteo
>>>
>>>  [[alternative HTML version deleted]]
>>>
>>> ------------------------------
>>>
>>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>>> https://stat.ethz.ch/mailman/listinfo/r-help