0

I am trying to make an array Z that have indexes of the most frequent occurring difference between two elements in the array X. So if the most frequent occurring difference between two elements in X is 3 then I would get all the indexes in X that have that difference into array Z.

x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6];
ct = 0;
difference_x = diff(x);
unique_x = unique(difference_x);
for i = 1:length(unique_x)
    for j = 1:length(x)
           space_between_elements = abs(x(i)-x(i+1));
           if space_between_elements  == difference_x
                ct = ct + 1;
                space_set(i,ct) = j;
           end
     end
end

I Don´t get the indexes of X containing the most frequent difference from this code.

  • 2
    Please also type out the solution that you want - your description is unclear. Does the nested loop you posted post the correct answer? Either way what is your problem with your code. – Dan Jul 15 '14 at 10:16

1 Answers1

0

It appears you want to find how many unique differences there are, with "difference" interpreted in an absoulte-value sense; and also find how many times each difference occurs.

You can do that as follows:

x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6]; %// data
difference_x = abs(diff(x));
unique_x = unique(difference_x); %// all differences
counts = histc(difference_x, unique_x); %// count for each difference

However, comparing reals for uniqueness (or equality) is problematic because of finite precision. You should rather apply a tolerance to declare two values as "equal":

x = [ 0.2 0.4 0.6 0.4 0.1 0.2 0.2 0.3 0.4 0.3 0.6]; %// data
tol = 1e-6; %// tolerance
difference_x = abs(diff(x));
difference_x = round(difference_x/tol)*tol; %// apply tolerance
unique_x = unique(difference_x); %// all differences
counts = histc(difference_x, unique_x); %// count for each difference

With your example x, the second approach gives

>> unique_x
unique_x =
         0    0.1000    0.2000    0.3000
>> counts
counts =
     1     4     3     2
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • How would I collect the indices of the array X using the highest unique_x counts. Something like index = find(counts==max(counts)); if unique_x(index)==difference_X % collects the index number in X end – user3840315 Jul 15 '14 at 12:03