Building matrix of differences
7 views (last 30 days)
Say I have a vector v=[v1,...,vn].'. How can I generate the matrix D with components D(i,j) = vi - vj ? The dimension of the vector n is very large, so efficiency matters. Ideally I would like to generate the following matrix E(i,j) = 1/(vi-vj) for vi ~= vj (which we may assume corresponds to i~=j) and E(i,i) = 0.
Is there a fast way to do it? Doing it with loops is very slow.
Thanks a lot,
Star Strider on 19 May 2017
See if this does what you want:
v = randi(9, 1, 5); % Create Data
D = bsxfun(@minus, v, v'); % Subtract To Create Matrix
Dnz = D~=0; % Logical Matrix (Becomes Numeric)
Dinv = Dnz./D; % Element-Wise ‘Inverse’
Note that ‘0/0’ become NaN values.