How to describe this matlab code with mathematical notation?

68 Views Asked by At

I need your help to describe the following matlab code in a scientific way:

function [y,x]= select1()
  x=10*rand(1,7); 
  m=[3 7];
  dif1=abs(m(1)-x);
  dif2=abs(m(2)-x);
  if (sum(dif1(:)<dif2(:)) > 
      sum(dif1(:)>dif2(:)));
    y= m(1);
  else
    y= m(2);
end

I understand that this function selects m1 if most of x values are closer to m1 than to m2, and selects m2 else, but I am having a hard time describing its steps properly with mathematical notation.

1

There are 1 best solutions below

0
On BEST ANSWER

It is a binary choice.

  1. 7 uniformly selected random numbers between 0 and 10 are generated
  2. We count how many are closer by absolute value to 3 than to 7.
  3. If the majority is closest to 3 then we select 3. If the majority is closer to 7, then we select 7.

Here is a more concise and general way to write it

  x = 10*rand(1,7);
  m = [3 7];
  [~,id] = max(sum(abs(m'-x)==min(abs(m'-x)),2));
  y = m(id);

You can now add arbitrary many values into m and it will still work.

You might need to use repmat to get it to work in older versions of Matlab which have not adopted Octaves "automatic broadcasting".