3

M is an affine transformation matrix that can transform coordinates from one coordinate system to another as follows:

v_old = [ x_old y_old z_old 1];
v_new = M * v_old;
% v_new contains [ x_new y_new z_new 1 ]

Now, I've got coordinates on the form of ndgrid/meshgrid:

[ X_old Y_old Z_old ] = ndgrid( 0:15 ); % for instance

How can I convert these to X_new etc?

I could do it with three for-loops loop (X_old(i,j,k) corresponds to x_old above) but there must be a better solution.

Anna
  • 2,645
  • 5
  • 25
  • 34

1 Answers1

2

You just have to rearrange the values so that each point has its four coordinates in one row:

result = [X_old(:) Y_old(:) Z_old(:) ones(numel(X_old),1)] * M;

Each row of result gives the new coordinates of each point.

Note that this works because multiplying matrix A times matrix B is the same as multiplying each row of A times B.

Or, if you can't afford to build the above matrix (because of memory limitations), use

result = X_old(:)*M(1,:) + Y_old(:)*M(2,:) + Z_old(:)*M(3,:) + ones(numel(X_old),1)*M(4,:);

In either case, if you want to rearrange the result so that it has the same size as X_old, Y_old, Z_old, use this as a last step:

s = size(X_old);
X_new = reshape(result(:,1), s);
Y_new = reshape(result(:,2), s);
Z_new = reshape(result(:,3), s);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    Neat! I've got a very large matrix, though (X_old is 512x512x300), so I can't afford to create that matrix while I've still got the ndgrid results. – Anna Mar 04 '14 at 15:02
  • ("afford" as in "keep in RAM") – Anna Mar 04 '14 at 15:06
  • @Anna In that case you might need a loop that builds each row of the matrix: `result(ii,:) = [X_old(ii) Y_old(ii) Z_old(ii) 1] * M;` where `ii` is the loop variable (from `1` to `numel(X)`). Or build the matrix in chunks, using as many rows per chunk as you can afford – Luis Mendo Mar 04 '14 at 15:07
  • @Anna I think I found a way. Please see updated answer – Luis Mendo Mar 04 '14 at 21:58
  • Thanks. I tried your update though, but the results are not the same as with the other method. The fourth column isn't even all ones. – Anna Mar 05 '14 at 14:50
  • 2
    Ah, `M` must be transposed. Thank you! – Anna Mar 05 '14 at 14:51