[R] simple matrix calculation

(Ted Harding) Ted.Harding at wlandres.net
Thu Mar 29 00:30:56 CEST 2012


On 28-Mar-2012 Kehl Dániel 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
> - Multiply A1*B and get a scalar, the first element of my new 3x3 matrix.
> 
> I could do that with loop. Can you suggest something that is more 
> elegant and faster?
> 
> Thank you
> Daniel

It looks as though you want to do this for each of the 3x3 matrices.
A possible solution could be on the following lines. For compactness
I have reduced your problem to a 4x4 matrix A divided into 4 2x2 blocks.

A:
  A11 A12 A13 A14
  A21 A22 A23 A24
  A31 A32 A33 A34
  A41 A42 A43 A44

If you post-multiply the matrix A by the 4x2 matrix S:

S:
  1  0
  1  0
  0  1
  0  1

then A%*%S gives you

  R11  R12
  R21  R22

where Rij is the 2x1 matrix of row-sums of block (i,j) of A, e.g.

R12:
  A13+A14
  A23+A24

Similarly, if you have a vector B of length 2:

B:
  b1
  b2

and you set up the 4x2 matrix BB:

BB:
  b1  0
  b2  0
  0   b1
  0   b2

then A%*%BB is a 2x2 matrix

  BB11 BB12
  BB21 BB22

where BBij is the result of {Block[i,j] of A}%*%B:

A%*%BB:
  A11 A12 A13 A14 %*%  b1 0
  A21 A22 A23 A24      b2 0
  A31 A32 A33 A34      0  b1
  A41 A42 A43 A44      0  b2

E.g.
BB12:
  A13*b1 + A14*b2
  A23*b1 + A24*b2

This generalises immediately to your 9x9 and a 3-vector.
Setting up the matrices S and BB should be straightforward
(and once done can be applied to any matrix A).

Does this help?

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 28-Mar-2012  Time: 22:30:45
This message was sent by XFMail



More information about the R-help mailing list