用matlab / octave制作动画图

时间:2014-11-04 04:06:52

标签: matlab octave

我试图为这个等式绘制一个动画,请参阅下面我试图为它设置动画为b> 300> = b< = 486

clear all, clc,clf,tic
m=3.73;
a=480;
b=486;
r=1;
fs=44100;
x=linspace(0,2*pi,fs)';
y=m^3*cos(sqrt(a*r*x)).^(0.77)/r + m^3*cos(sqrt(b*r*x)).^(0.77)/r-20;
normalize_y=(y/max(abs(y))*0.8);
plot(x,y)

我使用octave 3.8.1,这是matlab的克隆

3 个答案:

答案 0 :(得分:1)

将您的绘图代码放在for循环中,b作为迭代变量,然后放置pause一小段时间。之后,绘制图表,然后使用drawnow刷新图表。换句话说,请尝试此代码。我在您的代码中添加了%// Change个注释,我引入了新的行:

m=3.73;
a=480;
r=1;
fs=44100;
x=linspace(0,2*pi,fs)';
figure;
for b = 300 : 486 %// Change
    y=m^3*cos(sqrt(a*r*x)).^(0.77)/r + m^3*cos(sqrt(b*r*x)).^(0.77)/r-20;
    normalize_y=(y/max(abs(y))*0.8);
    pause(0.1); %// Change
    plot(x,y);
    title(['b = ' num2str(b)]); %// Change
    drawnow; %// Change
end

作为奖励,我已经将b的当前值放在每个绘图的位置。顺便说一句,我不知道你不使用它时代码中有normalize_y的原因。你的意思是用normalize_y代替y吗?只是一个想法。无论如何,尝试一下,看看它看起来如何。祝你好运!

答案 1 :(得分:0)

另一个解决方案是使用绘图的句柄,然后只更新绘图的'YData' - 属性。这对于更复杂的图表尤其有用,其中有超过1行,但您只想更改一行。此外,Axis标签不会被覆盖,这通常可以防止很多开销。 在Matlabcode中它看起来像这样:

% // Parameter and x-range
m=3.73;
a=480;
r=1;
fs=44100;
x=linspace(0,2*pi,fs)';
% // function to compute y for given x and parameter b
f = @(x, b) m^3*cos(sqrt(a*r*x)).^(0.77)/r + m^3*cos(sqrt(b*r*x)).^(0.77)/r-20;

% // first plot out of loop (to get plot handle)
figure;
b = 300;
y = f(x, b);
handle = plot(x, y);
xlabel('x') % // only set once
ylabel('y=f(x,b)') % // only set once
title(['b = ' num2str(b)]);
pause(0.1);

% // animate for b = 301 to 86
for b = 301:486 %// Change
    set(handle, 'YData', f(x, b)) % set new y-data in plot handle
    pause(0.1); %// update plot
    title(['b = ' num2str(b)]); %// update title
end

答案 2 :(得分:0)

这适用于八度音阶3.8.1

% // Parameter and x-range
m=3.73;
a=480;
r=1;
fs=44100;
x=linspace(0,2*pi,fs)';
% // function to compute y for given x and parameter b
f = @(x, b) m^3*cos(sqrt(a*r*x)).^(0.77)/r + m^3*cos(sqrt(b*r*x)).^(0.77)/r-20;

% // first plot out of loop (to get plot handle)
figure;
b = 300;
y = f(x, b);
handle = plot(x, y);
xlabel('x') % // only set once
ylabel('y=f(x,b)') % // only set once
title(['b = ' num2str(b)]);
pause(0.1);

% // animate for b = 301 to 86
for b = 301:486 %// Change
    %set(handle, 'YData', f(x, b)) % set new y-data in plot handle

    %To work with octave 3.8.1 use the line below
    set(handle, 'YData', real (f(x, b)))

    pause(0.1); %// update plot
    title(['b = ' num2str(b)]); %// update title
end