8 views (last 30 days)

Show older comments

I have to make a coordinates transformation between two reference systems (axes). For it, three matrices (3x3) have to be multiplied due to some intermediate axes are used. I have thought two approaches to resolve this:

method #1: Making the multiplication directly, i.e. v_f = R1*R2*R3*v_i

method #2: Split into steps.

step 1: v_3i = R3*v_i

step 2: v_23 = R2*v_3i

step 3: v_f = R1*v_23

where: R1, R2 and R3 are 3x3 matrices

v_f,v_i, v_3i, v_23 are 3x1 vectors

I would like to know what method is more efficient computationally (less time) to do the transformation (this will be made a lot of times).

Teja Muppirala
on 14 May 2012

I think you might be better off grouping your multiplications so that you maximize matrix-vector products instead of matrix-matrix products.

For example:

R1 = rand(3);

R2 = rand(3);

R3 = rand(3);

v = rand(3,1);

tic;

for n = 1:1e6, R1*R2*R3*v; end;

toc;

% Slightly faster

tic;

for n = 1:1e6, R1*(R2*(R3*v)); end;

toc;

This is especially true for larger matrices much bigger than 3x3.

R1 = rand(1000);

R2 = rand(1000);

R3 = rand(1000);

v = rand(1000,1);

tic;

R1*R2*R3*v;

toc;

% Much faster

tic;

R1*(R2*(R3*v));

toc;

Of course if the R's are all constant and you are reusing them, then you should just multiply them all together and store that result to begin with.

Jan
on 14 May 2012

There is no difference internally. The intermediate results have to be calculated in both cases. A TIC/TOC measurement allows you to find out, which one is faster.

Usually it is possible to calculate R1*R2*R3 explicitely without a matrix multiplication.

[EDITED, appended after your comment]:

function R = RotMatrix(N, A)

% N: [1 x 3], normalized vector to rotate around

% A: [1 x 1], angle

% Calculate trigonometric values once to save time:

cA = cos(A);

sA = sin(A);

cmA = 1 - cA;

x = N(:, 1);

y = N(:, 2);

z = N(:, 3);

ysA = y .* sA; % Some optimizations to save products

zsA = z .* sA;

xsA = x .* sA;

xcmA = x .* cmA;

ycmA = y .* cmA;

yzcmA = z .* ycmA;

xycmA = x .* ycmA;

xzcmA = z .* xcmA;

R = [cA + x .* xcmA, xycmA + zsA, xzcmA - ysA; ...

xycmA - zsA, cA + y .* ycmA, yzcmA + xsA; ...

xzcmA + ysA, xsA - yzcmA, cA + z .* z .* cmA];

For a real application it could be more efficient to accept [nFrame x 3] arrays as list of vectors and a [nFrame x 1] list of angles. Then the context decides, which output dimensions are most useful, perhaps a [3 x 3 x nFrame] array or three [3 x nFrame] matrices, which allow a DOT product directly to transform vectors.

James Tursa
on 14 May 2012

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!