Using a for loop to determine the 3D distances between an array of points along a 2D plane and a single point in space.

I need to apply this formula to each of the points along a 2D plane: Distance = sqrt(((x2-x1).^2)+((y2-y1).^2)+((z2-z1).^2))
x1, y1 and z1 will all remain constant as they are the single point in space. Currently, I have the 2D plane's x,y & z coordinates stored in a 3 dimensional array.
This is the code I have got so far.
c= 343; % speed of sound
Rsize = 3; % Size of the Reflector plane
p= 20; % No. of points in reflector plane
Spacing = Rsize/p;
Fmax= 2*p; %Highest Freq. used in predictions
fs= 48000; %Sample Rate
[X, Z]= meshgrid(0:Spacing:Rsize); %Defining Reflector Plane
Y= zeros(size(X, 1));
Rplane = cat(3, X, Y, Z);
Xs= 1.5; % Source Position
Ys= 3;
Zs= 1.5;
Xr= 1.5; %Receiver Position
Yr= 0.5:0.5:3;
Zr=1.5;
%%Plot locations of elements
%hold
%mesh(X, Y, Z);
%plot3(Xs,Ys,Zs,'*');
%plot3(Xr,Yr,Zr,'*');
%%Distance Calculations
SXdist = zeros(size(Rplane));
for i = numel(Rplane);
SXdist(i) = sqrt( )
Any help getting my head around this would be greatly appreciated!

 Akzeptierte Antwort

T.A.
T.A. am 12 Aug. 2017
Bearbeitet: T.A. am 12 Aug. 2017
It looks like you've already got most of the answer. Assuming that Xs, Ys,and Zs are the coordinates of your point, and that X, Y, and Z are your 2D plane, you need to do this:
Distance = sqrt(((X-Xs).^2)+((Y-Ys).^2)+((Z-Zs).^2))
It will give you an 2D array with each entry corresponding to a distance from a point on the plane.
Why? Break it down into the steps of what's going on.
Make an array where each (i,j) entry is equal to X(i,j)-Xs. Note that when you add/subtract/multiply/divide a matrix and a scalar value, MATLAB automatically performs the operation element-wise. Repeat for Y and Z.
dX = X-Xs;
dY = Y-Ys;
dZ = Z-Zs;
Then take that dX array and make a new array where each entry (i,j) is equal to dX(i,j)^2 . Note that since the input is a matrix, we need to specify element-wise operation to get what we want. Repeat for Y and Z.
dXsq = dX.^2;
dYsq = dY.^2;
dZsq = dZ.^2;
Add all these together element-wise. sqrt works element-wise as well.
Distance = sqrt(dXsq + dYsq + dZsq);
So now each element (i,j) in Distance is equal to sqrt(X(i,j)^2 + Y(i,j)^2 + Z(i,j)^2)

2 Kommentare

Thank you! Looks like I was making far harder than it needed to be and thinking myself in circles haha.
You're welcome! I know the MATLAB vector notation might be tricky to wrap your head around at first, but if you ever need to process larger pieces of data it will run much faster than doing the same thing in a for loop.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Phased Array Design and Analysis finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 12 Aug. 2017

Kommentiert:

am 14 Aug. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by