You can convert it to an array and then use apply:
> mat1
[,1] [,2] [,3] [,4]
[1,] 3 2 12 4
[2,] 14 13 13 2
[3,] 15 9 6 9
[4,] 2 15 13 19
> mat2
[,1] [,2] [,3] [,4]
[1,] 0 11 10 7
[2,] 12 9 3 13
[3,] -4 13 0 14
[4,] -2 0 -4 -1
> mat3
[,1] [,2] [,3] [,4]
[1,] 20 6 16 23
[2,] 24 8 11 12
[3,] 15 13 6 16
[4,] 5 22 20 25
>
> x <- array(c(mat1,mat2,mat3), dim=c(4,4,3))
> apply(x,c(1,2),mean)
[,1] [,2] [,3] [,4]
[1,] 7.666667 6.333333 12.666667 11.33333
[2,] 16.666667 10.000000 9.000000 9.00000
[3,] 8.666667 11.666667 4.000000 13.00000
[4,] 1.666667 12.333333 9.666667 14.33333
On Mon, May 18, 2009 at 8:40 PM, dxc13 <[email protected]> wrote:
>
> useR's,
> I have several matrices of size 4x4 that I want to calculate means of their
> respective positions with. For example, consider I have 3 matrices given
> by
> the code:
> mat1 <- matrix(sample(1:20,16,replace=T),4,4)
> mat2 <- matrix(sample(-5:15,16,replace=T),4,4)
> mat3 <- matrix(sample(5:25,16,replace=T),4,4)
>
> The result I want is one matrix of size 4x4 in which position [1,1] is the
> mean of position [1,1] of the given three matrices. The same goes for all
> other positions of the matrix. If these three matrices are given in
> separate text files, how can I write code that will get this result I need?
>
> Thanks in advance,
> dxc13
> --
> View this message in context:
> http://www.nabble.com/how-to-calculate-means-of-matrix-elements-tp23607694p23607694.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> [email protected] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
[[alternative HTML version deleted]]
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.