Reputation: 2750
my question is quite trivial, but I'm looking for the vectorized form of it.
My code is:
HubHt = 110; % Hub Height
GridWidth = 150; % Grid length along Y axis
GridHeight = 150; % Grid length along Z axis
RotorDiameter = min(GridWidth,GridHeight); % Turbine Diameter
Ny = 31;
Nz = 45;
%% GRID DEFINITION
dy = GridWidth/(Ny-1);
dz = GridHeight/(Nz-1);
if isequal(mod(Ny,2),0)
iky = [(-Ny/2:-1) (1:Ny/2)];
else
iky = -floor(Ny/2):ceil(Ny/2-1);
end
if isequal(mod(Nz,2),0)
ikz = [(-Nz/2:-1) (1:Nz/2)];
else
ikz = -floor(Nz/2):ceil(Nz/2-1);
end
[Y Z] = ndgrid(iky*dy,ikz*dz + HubHt);
EDIT
Currently I am using this solution, which has reasonable performances:
coord(:,1) = reshape(Y,[numel(Y),1]);
coord(:,2) = reshape(Z,[numel(Z),1]);
dist_y = bsxfun(@minus,coord(:,1),coord(:,1)');
dist_z = bsxfun(@minus,coord(:,2),coord(:,2)');
dist = sqrt(dist_y.^2 + dist_z.^2);
Upvotes: 1
Views: 7958
Reputation: 45752
I agree with Tal Darom, pdist2
is exactly the function you need. It finds the distance for each pair of coordinates specified in two vectors and NOT the distance between two matrices.
So I'm pretty sure in your case you want this:
pdist2([Y(:), Z(:)], [Y(:), Z(:)])
The matrix [Y(:), Z(:)]
is a list of every possible coordinate combination over the 2D space defined by Y-Z. If you want a matrix containing the distance from each point to each other point then you must call pdist2
on this matrix with itself. The result is a 2D matrix with dimensions numel(Y)
x numel(Y)
and although you haven't defined it I'm pretty sure that both Y
and Z
are n*m
matrices meaning numel(Y) == n*m
EDIT:
A more correct solution suggested by @Shai is just to use pdist since we are comparing points within the same matrix:
pdist([Y(:), Z(:)])
Upvotes: 1
Reputation: 114966
I believe you should use pdist
rather than pdist2
.
D = pdist( [Y(:) Z(:)] ); % a compact form
D = squareform( D ); % square m*n x m*n distances.
Upvotes: 2
Reputation: 1409
You can use the matlab function pdist2
(I think it is in the statistics toolbox) or you can search online for open source good implementations of this function.
Also, look at this unswer: pdist2 equivalent in MATLAB version 7
Upvotes: 0