MATLAB: How to automatically specify a “Best Location” property for the textbox annotation function

bestco-ordinateslegendlocationMATLABtext;

Can I place a textbox annotation at the 'best' location of a plot instead of needing to manually specify the coordinates? I would like to do something like the following:
>> t = annotation('textbox', 'String', 'Hello', 'Location', 'best');
This results in an error because there is no Location property on the TextBox class.
The 'legend' function can use 'best' to intelligently decide where to place the graphic element on a plot. Additionally, it can specify the 'Location' to be in the cardinal directions of the plot such as 'east', 'southwest', etc. It would be great if there were similar functionality in a function which places only text on the plot.

Best Answer

To automatically place a text object at the 'Best' location similar to a 'legend' object, use the attached MATLAB function 'TextLocation'. To use this, execute the following steps:
1. Download the attached function and store it in a location that is in MATLAB path.
2. Call this function with required text after creating the figure. For example:
a. Insert the text 'Hello' in the 'best' location in the current figure:
plot(1:10);
TextLocation('Hello','Location','best');
b. Insert the text 'World' in the 'southwest' location in the current figure:
TextLocation('World','Location','southwest');
Please note that the use of this function will delete any legend currently in the figure window. If you wish to use a legend in your figure, please specify it after calling the 'TextLocation' function.