0

Below is my code, I want to calculate the hamming distance between my "inp" and each row in the a matrix and save these hamming distances in different variables.:

a=[1 1 1 1;1 0 1 1;1 1 0 0; 1 0 0 1]
inp=[0 1 0 1]
for i = 1:4
    D=a(i,:);
    ('dist%d',i)=pdist2(inp,D,'hamming')
    fprintf('\n')
    i=i+1;
end

This code is not working and I know that the ('dist%d',i) is the part that is wrong. However, I can't solve it. What i want to do is get the results as follows: dist1= , dist2= , dist3= , dist4= .And this is why I tied it with the "i" because it is my loop. Any ideas how can this be solved.

motaha
  • 363
  • 2
  • 5
  • 19

1 Answers1

0

It appears you confused printing with assignment of variables. In general: evaluate, assign to a variable, then print.

  • Although Matlab does not require this, it's a good practice to initialize the place where you will store the distances. I do it with dist = zeros(4,1) below.
  • Store each distance in dist(i), the ith element of the array.
  • After that, print a formatted string with i and dist(i).
  • You don't need i=i+1, the for loop does incrementing for you.

a=[1 1 1 1;1 0 1 1;1 1 0 0; 1 0 0 1];
inp=[0 1 0 1];
dist = zeros(4,1);
for i = 1:4
    D=a(i,:);
    dist(i)=pdist2(inp,D,'hamming');
    fprintf('dist%d = %f \n', i, dist(i))
end

Note that if the printout was the only goal, storing the results in dist would be unnecessary. You could just do

 fprintf('dist%d = %f \n', i, pdist2(inp,D,'hamming'))

then, without introducing the array dist.

  • Well, what I wanted is to save each distance in a different variable and the when I call one of these variables I get its value, which is the hamming distance. – motaha Mar 22 '15 at 22:31
  • You mean that you prefer to store the distances in variables like b,c,d,e instead of storing them in an array? I'd advise against doing that. But if you wish, the contents of array can be assigned to variables like here: [How do I do multiple assignment in MATLAB?](http://stackoverflow.com/q/2337126). That is: put `distcell = num2cell(dist); [b c d e] = distcell{:};` after the loop. –  Mar 22 '15 at 22:47
  • I know that this isn't preferable, but I am thinking of doing separate variables because I need to compare the distances. For example if I have an array of distances dist=[2 2 3 5] and want to find the minimum of this array and its index I use '[mindist,ind] = min(dist(:))' but this only gives me 2 which is the minimum and index "1" knowing that index 1 and 2 have the same minimum distance. So, if I found a function that can retrieve the indexes of all of the minimum values I would go for it. – motaha Mar 22 '15 at 23:05