# Multiply vectors in a matrix by a matrix

I have a matrix of vectors e.g.

mat1 = Table[Table[RandomReal, 2], n, n];


which is actually a matrix of cartesian coordiantes (x,y). I want to rotate the coordinate system multiplying each vector by a rotation matrix. I'm using

matRot = Map[RotationMatrix[3 Degree].# &, mat1, {2}];


However, this is very slow for larger matrices such as n = 2048. I believe there is a more efficient way.

• Map[RotationTransform[3. Degree], mat1, {2}] is still slow but faster.
– kglr
Jul 11, 2019 at 7:59

You can actually use Dot directly. It works in unintuitive ways with tensors.

n = 1000;
mat1 = Table[Table[RandomReal, {2}], {n}, {n}];

matRot = Map[RotationMatrix[3 Degree].# &,  mat1, {2}]; // AbsoluteTiming


{79.8211, Null}

matRot2 = Map[RotationTransform[3. Degree], mat1, {2}]; // AbsoluteTiming


{9.04459, Null}

matRot3 = mat1.RotationMatrix[3 Degree]\[Transpose]; // AbsoluteTiming


{0.072949, Null}

matRot == matRot2 == matRot3


True

EDIT: While this is not what you asked, might I suggest you build mat1 directly with RandomReal? Bottlenecks are probably elsewhere, but anyways.

SeedRandom;
mat1 = Table[Table[RandomReal, {2}], {n}, {n}]; // AbsoluteTiming


{0.638727, Null}

SeedRandom;
mat = RandomReal[1, {n, n, 2}]; // AbsoluteTiming


{0.015406, Null}

mat == mat1


True

• Using 3. Degree makes it even faster (+1)
– kglr
Jul 11, 2019 at 8:26
• Thank you, that's exactly what I'm looking for! :) Jul 11, 2019 at 8:33
n = 1000;
mat1 = Table[Table[RandomReal, {2}], {n}, {n}];

matRot = Map[RotationMatrix[3 Degree].# &,  mat1, {2}]; // AbsoluteTiming


{110.570004, Null}

matRot2 = Map[RotationTransform[3. Degree], mat1, {2}]; // AbsoluteTiming


{13.946951, Null}

matRot == matRot2


True