在 matlab 中绘制二维矩阵的行

Plot rows of a 2d matrix in matlab

我有一个二维矩阵 A (100 x 100),其中每一行都包含一个要绘制的信号。 我想在同一图中用不同颜色的每一行绘制所有信号。我怎样才能轻松做到这一点?

如果您实际上在 at the documentation 中寻找 plot,您会发现如果您将矩阵传递给它,它会将每一列作为单独的绘图对象绘制在相同的轴上。因此,您可以简单地将数据的转置传递给 plot.

% Example data
A = magic(10);

% Create a plot for each row
hplot = plot(A.');

这将使用下一种绘图颜色绘制每个信号。

如果你想确保你有所有不同的颜色,你可以使用颜色图(例如parula)为每个绘图明确设置不同的颜色。

set(hplot, {'Color'}, num2cell(parula(size(A, 1)), 2))

更新

如果你想标记你的地块,你可以简单地使用 legend 来做到这一点。

displaynames = arrayfun(@(x)sprintf('Plot %d', x), 1:size(A, 1), 'uni', 0);
set(hplot, {'DisplayName'}, displaynames.');

legend(hplot)

或者,如果您有太多图无法合理地放入图例中,您可以创建一个交互式图,当您将鼠标悬停在给定图上时,它会突出显示它。这是一个这样的例子。

htitle = title('');

set(gcf, 'WindowButtonMotionFcn', @(s,e)motionCallback(hittest(s)))
motionCallback(hplot(1));

function motionCallback(plt)
    % Don't do anything if not a line object
    [tf, ind] = ismember(plt, hplot);

    if ~tf; return; end

    set(hplot, 'linewidth', 1)
    set(plt, 'LineWidth', 3)
    set(htitle, 'String', sprintf('SelectedPlot: %d', ind))
    drawnow
end

结果