假设我有一个5x5矩阵。 矩阵的元素每秒都会改变(刷新)。
我希望能够实时显示矩阵(不是作为色图,而是显示网格中的实际值),并观察其中的值随着时间的推移而变化。
我将如何在MATLAB中这样做?
答案 0 :(得分:2)
我原本以为你可以用disp
来实现这个目标:
for i=1:10
A = rand(5, 5);
disp(A);
end
如果您的意思是在控制台中不希望重复输出,则可以在每次clc
呼叫之前添加disp
以清除控制台:
for i=1:10
A = rand(5, 5);
clc;
disp(A);
end
答案 1 :(得分:2)
clc
和disp
的组合是最简单的方法(由蒂姆回答),根据您的需要,这可能是您想要的“更漂亮”的方法。这不会那么快,但您可能会发现一些好处,例如无需清除命令窗口或无法对无花果进行颜色编码和保存。
使用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
答案 2 :(得分:0)
如果你想在图上显示矩阵,这很容易。只需制作一个转储矩阵并显示它。然后使用文本功能在图上显示矩阵。例如
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