7
$\begingroup$

I have a matrix of vectors e.g.

mat1 = Table[Table[RandomReal[1], 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.

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

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

n = 1000;
mat1 = Table[Table[RandomReal[1], {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[16];
mat1 = Table[Table[RandomReal[1], {2}], {n}, {n}]; // AbsoluteTiming

{0.638727, Null}

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

{0.015406, Null}

mat == mat1

True

$\endgroup$
  • 3
    $\begingroup$ Using 3. Degree makes it even faster (+1) $\endgroup$ – kglr Jul 11 at 8:26
  • $\begingroup$ Thank you, that's exactly what I'm looking for! :) $\endgroup$ – T. Rihacek Jul 11 at 8:33
2
$\begingroup$
n = 1000;
mat1 = Table[Table[RandomReal[1], {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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.