3
votes

I've got the following problem in Matlab:

Let's assume we have two matrices A and B with the same size, where each row (m) represents a dataset over time (n). Matrix A contains the reference data and Matrix B the data to be tested. I now want to compute the relative distance between each and every combination of rows in A and B using

d(m_i,m_j) = sqrt(sum((A(m_x,:)-B(m_y,:).^2))

Solving this via a for loop would result in

for m_x = 1:size(A,2)
    for m_y = 1:size(A,2)
        d(m_i,m_j) = sqrt(sum((A(m_i,:)-B(m_j,:).^2));
    end
end

Is there a more elegant (and maybe faster) way of doing so?

1

1 Answers

3
votes

Yes, there is. You can use pdist2 (see doc):

d = pdist2(A,B);

The entry d(m,n) is the distance between A(m,:) and B(n,:).