No BSD License  

Highlights from
Legend from DisplayName

from Legend from DisplayName by Kristian Svartveit
Adds legend with strings from DisplayName

legendFromDisplayName(h, varargin)
function varargout = legendFromDisplayName(h, varargin)
%legendFromDisplayName Display legend with names from DisplayName property
%   legendFromDisplayName(handle, varargin...) puts a legend on the axes in
%   handle. handle can be an array of handles to axes and/or figures. 
%   All other arguments are passed on to LEGEND() command.
%
%   Returns an array of handles to created legends.
%
%   See also  LEGEND

hAxes = findobj(h, 'type', 'axes');

hLegend = zeros(size(hAxes)); % Initialize empty legend handle array
for iAxes = 1:length(hAxes)
    % Find all lines that are in current axes and loop through them to get
    % their DisplayName
    hLines = findobj(hAxes(iAxes), 'type', 'line'); 
    eLegend = cell(length(hLines), 1);
    for iLines = 1:length(hLines)
        eLegend{iLines} = get(hLines(iLines), 'DisplayName');
    end
    hLegend(iAxes) = legend(hLines, eLegend{:},  varargin{:});
end
if nargout == 1
    % Return array of handles to all legends created if asked for
    varargout = hLegend;
end

Contact us at files@mathworks.com