如何在Matlab中正确地进行矢量化

时间:2013-02-27 18:29:54

标签: matlab vectorization

我设置了一段需要很长时间才能运行的代码。我阅读了mathworks网站上的矢量化页面。我在一个部分仍然有点困惑,是否有可能对我运行plane_intersect的部分进行矢量化?

Unvectorized

for N = 1:sizeDimages
    imPos = anaInfoSat(N).ImagePositionPatient;
    A2Z = imPos(3);
    A2Y = imPos(2);
    A2X = imPos(1);

    [upP1(N,:)]=plane_intersect([cosSx(1),cosSy(1),cosSz(1)],[uppersatX1,uppersatY1,uppersatZ1],crossS,[A2X,A2Y,A2Z]);
    [loP1(N,:)]=plane_intersect([cosSx(1),cosSy(1),cosSz(1)],[lowersatX1,lowersatY1,lowersatZ1],crossS,[A2X,A2Y,A2Z]);
end

我对矢量化的尝试,upP1是一个Nx3矩阵。我预先分配upP1矩阵。下面的代码返回有关尺寸不匹配的错误。 ImagePosition是1x3 matix。

N = 1:sizeDimages;
imPos = anaInfoSat(N).ImagePositionPatient;
A2Z = imPos(3);
A2Y = imPos(2);
A2X = imPos(1);

[upP1(N,:)]=plane_intersect([cosSx(1),cosSy(1),cosSz(1)],[uppersatX1,uppersatY1,uppersatZ1],crossS,[A2X,A2Y,A2Z]);
[loP1(N,:)]=plane_intersect([cosSx(1),cosSy(1),cosSz(1)],[lowersatX1,lowersatY1,lowersatZ1],crossS,[A2X,A2Y,A2Z]);

这是plane_intersect代码的一部分,应该足以让你知道它的作用。

function [P,N,check]=plane_intersect(N1,A1,N2,A2)
%plane_intersect computes the intersection of two planes(if any) 
% Inputs: 
%       N1: normal vector to Plane 1
%       A1: any point that belongs to Plane 1
%       N2: normal vector to Plane 2
%       A2: any point that belongs to Plane 2
%
%Outputs:
%   P    is a point that lies on the interection straight line.
%   N    is the direction vector of the straight line
% check is an integer (0:Plane 1 and Plane 2 are parallel' 
%                              1:Plane 1 and Plane 2 coincide
%                              2:Plane 1 and Plane 2 intersect)
%
% Example:
% Determine the intersection of these two planes:
% 2x - 5y + 3z = 12 and 3x + 4y - 3z = 6
% The first plane is represented by the normal vector N1=[2 -5 3]
% and any arbitrary point that lies on the plane, ex: A1=[0 0 4]
% The second plane is represented by the normal vector N2=[3 4 -3]
% and any arbitrary point that lies on the plane, ex: A2=[0 0 -2]
%[P,N,check]=plane_intersect([2 -5 3],[0 0 4],[3 4 -3],[0 0 -2]);

1 个答案:

答案 0 :(得分:3)

在你的矢量化代码中,anaInfoSat(N).ImagePositionPatient;不会返回单个答案,而是会返回几个答案。如果将resuts分配给单个变量,它将只收到第一个答案。这就是您得到尺寸不匹配错误的原因。

根据数据类别,您可以组合成矩阵

imPos = [anaInfoSat(N).ImagePositionPatient];

或进入单元格数组

imPos = {anaInfoSat(N).ImagePositionPatient};

您也可以同时分配多个变量:

[A2X, A2Y, A2Z] = anaInfoSat(1:3).ImagePositionPatient;