# Find differences in a set of points without a for loop

5 vues (au cours des 30 derniers jours)
Sonoma Rich le 21 Avr 2015
Commenté : Image Analyst le 19 Mai 2022
I a vector of numbers that I am trying to find the differences between each element in the vector without a for loop. Below is a code example. Is there a more efficient way to execute this code without a for loop?
x = rand(20,1);
diff = zeros(length(x),length(x));
for ix = 1:length(x)
for iy = (ix+1):length(x)
diff(ix,iy) = abs(x(ix) - x(iy));
end
end
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponses (3)

Image Analyst le 21 Avr 2015
Modifié(e) : Image Analyst le 21 Avr 2015
diff() is a built in function. Don't use it for a variable name.
For a microscopic length such as 20, don't worry about a for loop. It won't take any time at all, and in fact may take less than calling some fancy function.
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Image Analyst le 21 Avr 2015
Richard's "Answer" moved here since it is not an answer to the original question:
Thanks for the help. My actual code has a vector that is much larger. I was just using this as an example.

Connectez-vous pour commenter.

Mehri Mehrnia le 19 Mai 2022
I have the question to find all pair-wise difference in a group without loop!
My array in scale of milions!
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Image Analyst le 19 Mai 2022
Try using pdist2, pdist, or diff

Connectez-vous pour commenter.

Bruno Luong le 19 Mai 2022
Modifié(e) : Bruno Luong le 19 Mai 2022
x = randi(10,3,1)
x = 3×1
5 4 8
d = abs(x - x.')
d = 3×3
0 1 3 1 0 4 3 4 0
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements 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