2

I have two equal length strings containing 1's and 0's. Each string is 128-bits long, and I want to calculate the Hamming distance between them. What's the best way I can go about doing this?

e.g. a='1000001' and b='1110001' --> dist=Hamming(a,b);

Kara
  • 6,115
  • 16
  • 50
  • 57
GobiasKoffi
  • 4,014
  • 14
  • 59
  • 66

2 Answers2

6

Use pdist with the hamming parameter.

Donnie
  • 45,732
  • 10
  • 64
  • 86
  • 2
    Only thing to note is that this gives a fractional result, which is nonstandard. You'll need to multiply the result by `length(a)`. – Oliver Charlesworth Nov 14 '10 at 20:38
  • You also need to turn 1000001 into [1 0 0 0 0 0 0 1] in order to let pdist treat each digit separately – Code42 Sep 03 '17 at 04:36
5
dist = sum(a ~= b);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680