1

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.

Jean Marie
  • 81,803
  • 1
    I don't really get why you're getting downvoted. Seems like a reasonable question. Maybe the formatting could be improved. – JKEG Aug 28 '20 at 21:47
  • 2
    @JKEG This site isn't a code translation service. I do not think this question is on topic on this site. – amWhy Aug 28 '20 at 21:50
  • 1
    I'm not sure one can find any science at the background of this very peculiar script. – Jean Marie Aug 28 '20 at 22:03
  • 1
    The tag description for the [tag:matlab] tag reads "For mathematical questions about MATLAB; questions purely about the language, syntax, or runtime errors would likely be better received on Stack Overflow." This question is not asking a mathematical question; rather, it is asking about syntax. As indicated by the tag description, this question might be better received elsewhere in the SE network. – Xander Henderson Aug 28 '20 at 22:20

1 Answers1

1

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".

mathreadler
  • 25,824