在matlab中使用plot对象自动标题的绘图

时间:2014-09-09 12:16:17

标签: matlab plot

我想知道你们中的一些人是否知道如何使用对象的名称自动标题图

因此,当我绘制超级矩阵时(5:10,:,2:3) 情节上的标题(或图例......)说" supermatrix(5:10,:,2:3)"

谢谢

3 个答案:

答案 0 :(得分:1)

这是出于调试目的吗?如果没有,那么我建议你告诉我们你的整体动机,因为有人可能会建议一个更强大的方法,但这可能会让你开始:

vname = @(x)inputname(1); %//from here: https://www.mathworks.com/matlabcentral/newsreader/view_thread/251347
plot(supermatrix(5:10,:,2:3))
title(vname(supermatrix))

虽然老实说我无法想象为什么这会有用呢

答案 1 :(得分:1)

我认为这可以满足您的需求,而且非常灵活:

function h = plotwithtitle( plotstring, varargin )
   argstoplot = evalin('caller', ['{', plotstring, '}']);
   h = plot( argstoplot{:}, varargin{:} );
   title(plotstring);
end

以下示例对我有用:

supermatrix=rand(10,10);
x=1:10;
y=rand(1,10);

plotwithtitle('supermatrix');
plotwithtitle('supermatrix(5:10,:)');
plotwithtitle('x, y');
plotwithtitle('x, y', '--r');
plotwithtitle('1:10', 'r');
plotwithtitle('rand(1,10)');

答案 2 :(得分:1)

我修改了F.Moisy最初创建的函数dfig,用于创建停靠的数字,以便将用于绘图的命令显示在图名中。

这个想法是读取命令历史中的最后一个命令并使用它来生成图标题。

function hh = dfig(varargin)
%DFIG  Create docked figure window
%   DFIG, by itself, creates a new docked figure window, and returns its
%   handle.
%
%   DFIG(H) makes H the current figure and docks it.  If Figure H does not
%   exist, and H is an integer, a new figure is created with handle H.
%
%   DFIG(H, name, value,...) reads additional name-value pairs. See
%   doc(figure) for available otions.
%
%   DFIG will parse the command line input and use the text following dfig
%   as figure name. E.g. calling dfig,plot(x(1:3),y(2:2:end)) results in
%   the name "plot(x(1:3),y(2:2:end))"

%   F. Moisy, moisy_at_fast.u-psud.fr
%   Revision: 1.00,  Date: 2007/09/11
%   Modified (a lot) by Jonas


if nargin==0
    h=figure;    % create a new figure
else
    % call figure with varargin
    figure(varargin{:})
    h = gcf;

end

if ~any(strcmp('name',varargin(1:2:end)))
    % if no name has been supplied: try to use function call
    javaHistory=com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory;
    if ~isempty(javaHistory)
        lastCommand = javaHistory(end).toCharArray';
        funCall = regexp(lastCommand,'dfig\s*[,;]\s*(.*)$','tokens','once');
    else
        funCall = [];
    end
    if ~isempty(funCall)
        if isnumeric(h)
        set(h,'Name',[num2str(h),': ',funCall{1}],'NumberTitle','off')
        else % HG2
            h.Name = sprintf('%i: %s',h.Number,funCall{1});
            h.NumberTitle = 'off';
        end
    end
end

set(h,'WindowStyle','docked');  % dock the figure

if nargout~=0   % returns the handle if requested
    hh=h;
end