【发布时间】:2017-03-10 03:40:13
【问题描述】:
假设我有一个 5x5 矩阵。 矩阵的元素每秒都在变化(刷新)。
我希望能够实时显示矩阵(不是作为颜色图,而是在网格中显示实际值)并观察其中的值随着时间的推移而变化。
我将如何在 MATLAB 中这样做?
【问题讨论】:
假设我有一个 5x5 矩阵。 矩阵的元素每秒都在变化(刷新)。
我希望能够实时显示矩阵(不是作为颜色图,而是在网格中显示实际值)并观察其中的值随着时间的推移而变化。
我将如何在 MATLAB 中这样做?
【问题讨论】:
clc 和 disp 的组合是最简单的方法(由 Tim 回答),根据您的需要,这是您可能喜欢的“更漂亮”的方法。这不会那么快,但您可能会发现一些好处,例如不必清除命令窗口或能够对无花果进行颜色编码和保存。
使用dispMatrixInFig(此答案底部的代码),您可以在每个阶段的图形窗口(或唯一图形窗口)中查看矩阵。
示例测试代码:
fig = figure;
% Loop 10 times, pausing for 1sec each loop, display matrix
for i=1:10
A = rand(5, 5);
dispMatrixInFig(A,fig)
pause(1)
end
一次迭代的输出:
注释功能代码:
function dispMatrixInFig(A, fig, strstyle, figname)
%% Given a figure "fig" and a matrix "A", the matrix is displayed in the
% figure. If no figure is supplied then a new one is created.
%
% strstyle is optional to specify the string display of each value, for
% details see SPRINTF. Default is 4d.p. Can set to default by passing '' or
% no argument.
%
% figname will appear in the title bar of the figure.
if nargin < 2
fig = figure;
else
clf(fig);
end
if nargin < 3 || strcmp(strstyle, '')
strstyle = '%3.4f';
end
if nargin < 4
figname = '';
end
% Get size of matrix
[m,n] = size(A);
% Turn axes off, set origin to top left
axis off;
axis ij;
set(fig,'DefaultTextFontName','courier', ...
'DefaultTextHorizontalAlignment','left', ...
'DefaultTextVerticalAlignment','bottom', ...
'DefaultTextClipping','on');
fig.Name = figname;
axis([1, m-1, 1, n]);
drawnow
tmp = text(.5,.5,'t');
% height and width of character
ext = get(tmp, 'Extent');
dy = ext(4);
wch = ext(3);
dwc = 2*wch;
dx = 8*wch + dwc;
% set matrix values to fig positions
x = 1;
for i = 1:n
y = 0.5 + dy/2;
for j = 1:m
y = y + 1;
text(x,y,sprintf(strstyle,A(j,i)));
end
x = x + dx;
end
% Tidy up display
axis([1-dwc/2 1+n*dx-dwc/2 1 m+1]);
set(gca, 'YTick', [], 'XTickLabel',[],'Visible','on');
set(gca,'XTick',(1-dwc/2):dx:x);
set(gca,'XGrid','on','GridLineStyle','-');
end
【讨论】:
openvar('A'),它显示数组编辑器,该数组编辑器会在A发生任何更改时自动更新...看看linkdata可能也会很有趣如果愿意更新一些情节而不是可视化值
v = desktop.getGroupContainer('Variables'); 或 v = com.mathworks.mlservices.MLArrayEditorServices 通过命令来操作数组编辑器,但除了将数组版本设为只读之外,通过命令将变量的版本取消停靠在它自己的图形中太棘手了
drawnow 需要在循环期间更新图/变量
openvar('A'); for i=1:10 \\ A = rand(5, 5); drawnow; pause(1); \\ end(其中反斜杠表示换行),那么直到 10 秒后才会在变量中看到更新
我原以为你可以通过 disp 实现这一目标:
for i=1:10
A = rand(5, 5);
disp(A);
end
如果您的意思是您不希望在控制台中重复输出,您可以在每个 disp 调用之前包含一个 clc 以清除控制台:
for i=1:10
A = rand(5, 5);
clc;
disp(A);
end
【讨论】:
如果您想在图形上显示您的矩阵,这很容易。只需制作一个转储矩阵并显示它。然后使用文本功能在图形上显示您的矩阵。例如
randMatrix=rand(5);
figure,imagesc(ones(20));axis image;
hold on;text(2,10,num2str(randMatrix))
如果您想在 for 循环中执行此操作并查看数字变化,请尝试以下操作:
for i=1:100;
randMatrix=rand(5);
figure(1),clf
imagesc(ones(20));axis image;
hold on;text(2,10,num2str(randMatrix));
drawnow;
end
【讨论】:
num2str 中的字符串 (uk.mathworks.com/help/matlab/ref/num2str.html#btf97wr) 添加一些格式,以便每列具有相同的宽度,从而很好地对齐。