[R] simple matrix calculation

Kjetil Halvorsen kjetilbrinchmannhalvorsen at gmail.com
Thu Mar 29 02:52:57 CEST 2012


see inline.

On Wed, Mar 28, 2012 at 2:46 PM, Kehl Dániel <kehld at ktk.pte.hu> wrote:
> Dear list-members,
>
> I have a 9-by-9 matrix lets call it A with first row a11, a12, a13,..., a19
> etc.
> I also have a vector of length 3 (B).
> I want to construct a matrix of size 3x3 in the following way:
> - divide matrix A to 9 3x3 blocks
> - first is
>        a11, a12, a13
>        a21, a22, a23
>        a31, a32, a33
> - I want to get rowSums of this A1 matrix

A %*% C, where C is a 9x3 matrix
 A <- matrix(1:81, 9, 9)

> ones <- rep(1, 3)
> zeros <- rep(0, 3)
> C <- rbind(cbind(ones, zeros, zeros), cbind(zeros, ones, zeros), cbind(zeros, zeros, ones))
> C
      ones zeros zeros
 [1,]    1     0     0
 [2,]    1     0     0
 [3,]    1     0     0
 [4,]    0     1     0
 [5,]    0     1     0
 [6,]    0     1     0
 [7,]    0     0     1
 [8,]    0     0     1
 [9,]    0     0     1

> A %*%C
      ones zeros zeros
 [1,]   30   111   192
 [2,]   33   114   195
 [3,]   36   117   198
 [4,]   39   120   201
 [5,]   42   123   204
 [6,]   45   126   207
 [7,]   48   129   210
 [8,]   51   132   213
 [9,]   54   135   216






> - Multiply A1*B and get a scalar, the first element of my new 3x3 matrix.

But from your description I get the new matrix will be 9x3, as above?

> B <- 1:3
> A %*%C %*% B
      [,1]
 [1,]  828
 [2,]  846
 [3,]  864
 [4,]  882
 [5,]  900
 [6,]  918
 [7,]  936
 [8,]  954
 [9,]  972

> (A %*%C %*% B)[1]
[1] 828

Kjetil

>
> I could do that with loop. Can you suggest something that is more elegant
> and faster?
>
> Thank you
> Daniel
>
> ______________________________________________
> R-help at r-project.org 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.



More information about the R-help mailing list