Javascript syntax for array median?

javascript
statistics
scripting
Tags: #<Tag:0x00007fa30b31d700> #<Tag:0x00007fa30b31d340> #<Tag:0x00007fa30b31d020>

#1

Still struggling with learning java/javascript… Why does my code fail to find the median of this number array?

importClass(Packages.ij.IJ);
importClass(Packages.ij.util.ArrayUtil);
x=[2,1,2,5,4,3];
m=x.medianSort;    //tried medianSort(x) but that states medianSort is not defined
IJ.log(m);

The output is “undefined” and with no errors ?!? MedianSort is there in ArrayUtil Class, but still ‘not found’… API Code suggests it will do the sort and output the median. What am I doing wrong?
thanks for any insights.


#2

The medianSort() function is not static (see the API documentation), so you first have to instantiate an ArrayUtil object with your data and then call the medianSort() method of that object:

importClass(Packages.ij.util.ArrayUtil);

x=[2,1,2,5,4,3];
median = new ArrayUtil(x).medianSort();

print(median);

I agree that this is confusing because it’s a convention in the Java world that *Util classes contain static functions…


You can also use the Median class of Apache Commons Math, which is included in an up-to-date Fiji:

importClass(Packages.org.apache.commons.math3.stat.descriptive.rank.Median);

x=[2,1,2,5,4,3];
median = new Median().evaluate(x);

print(median);

#3

THANK YOU! I see I have a lot to learn going from macro language to higher level coding!