对于我的模拟,我需要计算许多转换矩阵,因此我想对我现在使用的 for 循环进行矢量化。
有没有办法对现有的 for 循环进行向量化,或者我之前可能需要另一种方法来计算向量和矩阵?
我准备了一个小的工作示例:
n_dim = 1e5;
p1_3 = zeros(3,n_dim); % translationvector (no trans.) [3x100000]
tx = ones(1,n_dim)*15./180*pi; % turn angle around x-axis (fixed) [1x100000]
ty = zeros(1,n_dim); % turn angle around y-axis (no turn) [1x100000]
tz = randi([-180 180], 1, n_dim)./180*pi; % turn angle around z-axis (different turn) [1x100000]
hom = [0 0 0 1].*ones(n_dim,4); % vector needed for homogenous transformation [100000x4]
% calculate sin/cosin values for rotation [100000x1 each]
cx = cos(tx)';
sx = sin(tx)';
cy = cos(ty)';
sy = sin(ty)';
cz = cos(tz)';
sz = sin(tz)';
% calculate rotation matrix [300000x3]
R_full = [ cy.*cz, -cy.*sz, sy; ...
cx.*sz+sx.*sy.*cz, cx.*cz-sx.*sy.*sz, -sx.*cy; ...
sx.*sz-cx.*sy.*cz, cz.*sx+cx.*sy.*sz, cx.*cy];
% prealocate transformation tensor
T = zeros(4,4,n_dim);
% create transformation tensor here
% T = [R11 R12 R13 p1;
% R21 R22 R23 p2;
% R31 R32 R33 p3;
% 0 0 0 1]
tic
for i = 1:n_dim
T(:,:,i) = [[R_full(i,1), R_full(i,2), R_full(i,3); ...
R_full(n_dim+i,1), R_full(n_dim+i,2), R_full(n_dim+i,3); ...
R_full(2*n_dim+i,1), R_full(2*n_dim+i,2), R_full(2*n_dim+i,3)], p1_3(:,i);
hom(i,:)];
end
toc