I'm producing m amount of nx1 vectors, and storing them all in an nxm matrix A (each column is a vector). What I want is to now create an mxm matrix B where B(i,j) = norm(vi -vj). I have a naive solution using nested for loops, but this takes far too long; I came up with a solution using 3d arrays but since I'm producing ~9000 vectors and each one is ~100000 entries, there's no way I have the memory for a 100000x9000x9000 array. Is there any other way to compute this?
Naive solution:
for i = 1:nvectors for j = i:nvectors dist = norm(vectorMatrix(:,i) - vectorMatrix(:,j)); distanceMatrix(i,j) = dist; distanceMatrix(j,i) = distanceMatrix(i,j); end end
3d array solution:
vectorMatrix = repmat(vectorMatrix, 1,1,nvectors); distanceMatrix(:,1,:) = vectorMatrix(:,:,1); distanceMatrix = repmat(distanceMatrix,1,nvectors,1); distanceMatrix = distanceMatrix - vectorMatrix; distanceMatrix = sqrt(sum(distanceMatrix.^2,1));
Best Answer