Ben Fossen
Ben Fossen

Reputation: 1007

How to properly vectorize in Matlab

I have a set a section of code that is taking a long time to run. I read over the vectorization page on the mathworks site. I am still a little confused on one part, is it possible to vectorize the part where I run 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

My attempt at vectorization, the thing is upP1 is a Nx3 matrix. I preallocate the upP1 matrix. This code below returns an error about dimension mismatch. ImagePosition is a 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]);

Here is part of the plane_intersect code, should be enough to let you know what it does.

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]);

Upvotes: 0

Views: 122

Answers (1)

yuk
yuk

Reputation: 19870

In your vectorized code anaInfoSat(N).ImagePositionPatient; won't return a single, but several answers. If you assign the resuts to a single variable it will receive only the first answer. This is why you get dimension mismatch error.

Depending on the data class you can combine into a matrix

imPos = [anaInfoSat(N).ImagePositionPatient];

or into a cell array

imPos = {anaInfoSat(N).ImagePositionPatient};

You can also assign to several variables as the same time:

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

Upvotes: 3

Related Questions