The scaleruler function in the Mapping Toolbox is clunky and difficult to work with. The scalebar function presented here is simple and intuitive. See the documentation file to the right for function Syntax, Description, and Examples.
Thanks for the feedback. The difference you see between scalebar and scaleruler is not an indication that either function is correct or incorrect. Rather, it just means the different scales are referenced to different places in the map. Each one is correct somewhere in the map, so as a general rule of thumb, if scalebar and scaleruler do not agree, the map is probably too big to include either.
Some GIS style guides say every map should include a graphical reference scale, but you've found the reason that's bad advice. Maps of large areas contain tremendous distortion yet a graphical reference scale implies the scale is true everywhere in the map. Africa is 14 times the size of Greenland, yet Mercator maps give the impression that Greenland is larger.
I suspect you may have found a fudge factor to make scalebar and scaleruler agree when neither should be used.
I could observe large scale length difference between your proposal and the function in the mapping tool... especially if the mapped area is far from the projection origin and combined with a global projection (like mercator).
I could manage this error changing the way you estimate the dstpermapunit on lines 143 and 144 to this proposal:
[lat2,lon2]=minvtran(xl(1) + 0.1,mean(yl));
Shoot, I neglected to mention--As of the July 25, 2015 update, scalebar now requires the pathdist function, which can be found on the File Exchange site here: http://www.mathworks.com/matlabcentral/fileexchange/47042
Added automatic length scaling, and now supports just about any length unit.
Inclusion of example file.