如何将仿射变换(4x4矩阵)应用于ndgrid / meshgrid结果? [英] How to apply an affine transformation (4x4 matrix) to ndgrid/meshgrid results?
问题描述
$ $ p是一个仿射变换矩阵,它可以将坐标从一个坐标系转换到另一个坐标系:
v_old = [x_old y_old z_old 1];
v_new = M * v_old;
%v_new包含[x_new y_new z_new 1]
现在, ndgrid / meshgrid的形式:
[X_old Y_old Z_old] = ndgrid(0:15); %例如
如何将这些转换为 X_new
etc?
我可以用三个for循环循环( X_old(i,j,k)
对应于上面的 x_old
),但是必须有更好的解决方案。
您只需重新排列值,以便每个点在一行中具有四个坐标:
result = [X_old( :) Y_old(:) Z_old(:) ones(numel(X_old),1)] * M;
每行结果
给出新坐标注意这是因为矩阵 A
乘以矩阵 B $ b / code>与每行乘以
A
次 B
。
或者,如果您无法构建上述矩阵(由于内存限制),请使用
<$ (1,:) + Y_old(:)* M(2,:) + Z_old(:)* M(3,:) + ones(numel(X_old),1 )* M(4,:);
在任何一种情况下,如果要重新排列结果以使其与 X_old
, Y_old
, Z_old
,将其作为最后一步:
s = size(X_old);
X_new = reshape(result(:,1),s);
Y_new = reshape(result(:,2),s);
Z_new = reshape(result(:,3),s);
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.
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);
这篇关于如何将仿射变换(4x4矩阵)应用于ndgrid / meshgrid结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!