matlab更新循环内的两组子图

时间:2015-06-05 13:32:33

标签: matlab matlab-figure matlab-guide

我有两组子图。我想在循环中更新它们。例如,

 % first figure
 f1 = figure;
 f11 = subplot(1,2,1), plot(a1);
 f12 = subplot(1,2,1), plot(b1);


 % second figure
 f2 = figure;
 f21 = subplot(1,2,1), plot(a2);
 f22 = subplot(1,2,1), plot(b2);

 for i = 1:3
      calculate a1, b1;
      update subplots in f1;

      calculate a2, b2;
      update subplots in f2;
 end

我该怎么做?

2 个答案:

答案 0 :(得分:2)

获取plot个对象的句柄,更新其'YData'属性,然后调用drawnow以确保刷新数字。 (另一种方法是每次简单地重新绘制图,但这可能更慢)。

请注意,在以下代码中,我还将两个subplot行更改为commented by @SanthanSalai,并将变量i更改为navoid shadowing the imaginary unit

%// first figure
f1 = figure;
f11 = subplot(1,2,1), h11 = plot(a1);
f12 = subplot(1,2,2), h12 = plot(b1);

%// second figure
f2 = figure;
f21 = subplot(1,2,1), h21 = plot(a2);
f22 = subplot(1,2,2), h22 = plot(b2);

for n = 1:3
    %// calculate a1, b1;
    set(h11, 'YData', a1);
    set(h12, 'YData', b1);

    %// calculate a2, b2;
    set(h21, 'YData', a2);
    set(h22, 'YData', b2);
end

答案 1 :(得分:1)

如路易斯所述,循环中的子图可以通过在预定义图之后使用'Ydata'来更新。

我遇到了类似的问题,我只是想分享一个扩展的例子。

% create two sets of data;
a1 = zeros(2,1)
b1 = zeros(2,1)
a2 = zeros(2,1)
b2 = zeros(2,1)

% first figure
f1 = figure;
f11 = subplot(1,2,1), h11 = plot(a1);
f12 = subplot(1,2,2), h12 = plot(b1);

% second figure
f2 = figure;
f21 = subplot(1,2,1), h21 = plot(a2);
f22 = subplot(1,2,2), h22 = plot(b2);

% apply a y limit, used only to enhance the plots
set(f11,'ylim',[-3 3])
set(f12,'ylim',[-3 3])
set(f21,'ylim',[-3 3])
set(f22,'ylim',[-3 3])

for n = 1:3

    % calulate a1 and b1
    a1(end) = a1(end)+1
    b1(end) = b1(end)-1

    set(h11, 'YData', a1);
    set(h12, 'YData', b1);

    % calculate a2, b2;
    a2 = -a1
    b2 = -b1

    set(h21, 'YData', a2);
    set(h22, 'YData', b2);

    pause(1)
end