[R] Matrix addition function

Vitalie S. vitosmail at rambler.ru
Thu Aug 13 17:01:48 CEST 2009


On Thu, 13 Aug 2009 15:11:03 +0200, Michael Knudsen <micknudsen at gmail.com>  
wrote:

> On Thu, Aug 13, 2009 at 11:35 AM, Lina Rusyte<linera27 at yahoo.co.uk>  
> wrote:
>
> Hi Lina,
>
>> What function can I use for matrices addition? I couldn’t find any  
>> information about it in the manual or in the internet.
>> (A+B suits, when the number of matrixes is small, function sum()  
>> doesn’t suit for matrices addition, because it sums all variables in  
>> the matrices and produces as an answer single number, not a matrix).
>

Reduce is the function you need. It can be applied to any operator not  
just `+`:

> M_list <- replicate(4, matrix(1, 2, 2), simplify=FALSE)
> M_list
[[1]]
      [,1] [,2]
[1,]    1    1
[2,]    1    1

[[2]]
      [,1] [,2]
[1,]    1    1
[2,]    1    1

[[3]]
      [,1] [,2]
[1,]    1    1
[2,]    1    1

[[4]]
      [,1] [,2]
[1,]    1    1
[2,]    1    1

> Reduce(`+`, M_list)
      [,1] [,2]
[1,]    4    4
[2,]    4    4
>



> I don't know of any function doing that, but you could easily write a
> one yourself. Suppese that X is a list of matrices. Then you could
> e.g. do as follows:
>
> matrixSum = function(X)
> {
>    N = length(X)
>    if (N==2) return(X[[1]]+X[[2]])
>    else return(matrixSum(X[[1:(N-1)]],X[[N]]))
> }
>
> I guess that one should do the trick.
>
> Best,
> Michael
>


--




More information about the R-help mailing list