Vectorizing and preallocating these "for" loops

1 view (last 30 days)
I'm a fairly new MATLAB user and I'm having trouble with speeding up my code. There are two m-files that need to be improved for this assignment I am doing. My professor put emphasis on addressing the "for" loops in the code, but no matter what I tried I'm not having much success.
The first m-file follows:
N = length(x(:,1)); %# points
xScaled = [x(:,1)-min(x(:,1)) x(:,2)-min(x(:,2))]; %subtract minimum from each [x,y]
xGrid = xScaled./h; %normalize
xGrid = floor(xGrid); %quantize to grid
xGrid = xGrid+1; %add 1 because matlab is 1's based
%the lowest grid value will be (1,1);
%this can be converted to a linear index
%determine number of grid cells in x and y directions
nMax = max(xGrid);
xIndex = xGrid(:,2)+nMax(2)*(xGrid(:,1)-1); %index = yCoord+height*xCoord
influence = zeros(N,1);
for ind1 = 1:N
tempInfluence = 0;
neighboorhoodPoints = findNeighboorsv2(ind1,x,xGrid,xIndex);
for ind2 = 1:length(neighboorhoodPoints(:,1)); %only loop over nearby particles
tempInfluence = tempInfluence+computeInfluence(x(ind1,:),neighboorhoodPoints(ind2,:),h);
if (x(ind1,1)~=neighboorhoodPoints(ind2,1)) %make sure they are not the same point
tempInfluence = tempInfluence+computeInfluence(x(ind1,:),neighboorhoodPoints(ind2,:),h);
end
end
influence(ind1) = tempInfluence;
end
And the second m-file follows:
%find which bin it is in
targetBin = xGrid(pt,:);
nMax = max(xGrid);
neighboorhoodPoints = [];
%gather points in adjacent bins
for ind1 = [targetBin(1)-1:1:targetBin(1)+1]
for ind2 = [targetBin(2)-1:1:targetBin(2)+1]
if (ind1>0 && ind1<=nMax(1) && ind2>0 && ind2<=nMax(2)) %only check over valid grid cells
%determine equivlant index
index = ind2+nMax(2)*(ind1-1); %convert ind1 & ind2 into
neighboorhoodPoints = [neighboorhoodPoints; x(xIndex==index,:)]; %find returns the indices where the expression is true
end
end
end
Any help and advice would be extremely beneficial! Thank you

Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!