MATLAB: Creating a Matrix from Distances between Vectors

MATLAB

I start with a 3 x 46 array where each 3 x1 column in the array is viewed as a position vector of a point, let's say the first vector in the array is p_1, the next one is p_2.
I also have a 3 x 100 array, which I am viewing as the position vectors of 100 points (where these points are always of a lower 'radius' than the points in the 3 x 46 array). I basically need to create a matrix which looks as follows, where each distance is the row vector obtained by vector subtraction of the two vectors:
[Distance from p_1 to first vector in the 3 x 100 array Distance from p_1 to second vector etc ]
[Distance from p_2 to first vector in the 3 x 100 array Distance from p_2 to second vector etc ]
[ Distance from p_3 ….. ]
and so on, until all the positions in the 3 x 46 array are covered, let me know if my intention is not clear.

Best Answer

This can be achieved easily without a loop:
%demo data
m = 46
n = 100
A = rand(3,m)
B = rand(3,n)
distance = sqrt(sum((permute(A, [2, 3, 1]) - permute(B, [3, 2, 1])).^2, 3));
The result is a mxn matrix. It basically moves the (X, Y, Z) of each point into the 3rd dimension for both matrix, and move the 2nd dimension of the 1st matrix into the 1st. So points in A are along the rows, and points in B are along the column (and coordinates across the 3rd for both). We now have compatible array sizes, so can create a 3D matrix of (Xa-Xb, Ya-Yb, Za-Zb) for all the points. Square that, sum across (X, Y, Z) so it reduces to a 2D matrix, and take the square root for the distance.
Or, if you have the stats toolbox, you can use pdist2.
edit: Note that if you want to store the vectors between the points as suggested by Jon instead of the distance (norm of the vectors), then it's simply:
vectors = permute(A, [2, 3, 1]) - permute(B, [3, 2, 1])
vectors(p1, p2, :) is the vector between point A(:, p1) and point B(:, p2).