Search code examples
matlabmatrixvectormetric

Easy way to get metric matrix in Matlab


Let's say I have a vector of strings and I wrote a function which find a distance between two strings.

I want to get the matrix of distances determined by this function. I know the brute-force way of doing it with loops but is there another simplier path?

For example:

my function:

function [value] = func(str1, str2)
    value = abs(str1(1) - str2(1))
end

the grueling way of getting the metric matrix

v = ['str'; 'rew'; 'ter'];
num = length(v);
metrMat = zeros(num);
for ii = 1:num
    for jj = 1:num
        metrMat(ii,jj) = func(v(ii),v(jj));
    end
end
metrMat

>metrMat =

>     0     1     1
>     1     0     2
>     1     2     0

Solution

  • This would be one vectorized approach with bsxfun -

    metrMat = abs(bsxfun(@minus,v(:,1),v(:,1).'))
    

    Sample run -

    >> v
    v =
    str
    rew
    ter
    >> metrMat = abs(bsxfun(@minus,v(:,1),v(:,1).'))
    metrMat =
         0     1     1
         1     0     2
         1     2     0