Effacer les filtres
Effacer les filtres

Building matrix of differences

2 vues (au cours des 30 derniers jours)
Lorenzo
Lorenzo le 19 Mai 2017
Commenté : Star Strider le 19 Mai 2017
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,
L

Réponses (1)

Star Strider
Star Strider le 19 Mai 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.
  2 commentaires
Lorenzo
Lorenzo le 19 Mai 2017
Thanks this is pretty good! I was using a combination of meshgrid, cat and reshape but this is more slick. Do you know a way to convert the Nan into zeroes? Unfortunately it still seems to be slower than half of the double loop. I will wait a little bit to see if there are more answer and then accept this one. Thanks again!
Star Strider
Star Strider le 19 Mai 2017
My pleasure!
To convert the NaN values to 0, add this assignment to my previous code:
Dinv(~Dnz) = 0; % Convert ‘NaN’ To ‘0’

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by