Matlab:如何在计算值时绘制值?

时间:2017-05-18 10:21:55

标签: matlab plot

matlab中是否有任何方法可以随时绘制值?以某种方式通过绘图函数x和y值一次?我有一个非常昂贵的循环,我认为在循环中直接使用绘图的唯一方法(我想我在某人的代码中看到这个)可能会将每个y值保存在一个数组中。但是,这会给我一个错误,例如: Attempted to access Y(1.00202); index must be a positive integer or logical.

示例代码:

function n = get_nodes(x_s, x_e, e_k)
    y_prev = 0; y_curr = 1;
    h = 10^-5;
    n = 0;
    for x = x_s+0.1:h:x_e-0.1
        a = 2 + (5/6)*forcing(x, e_k)*h^2;
        b = 1 - (1/12)*forcing(x-h, e_k)*h^2;
        c = 1 - (1/12)*forcing(x+h, e_k)*h^2;
        y_next = (a * y_curr + b * y_prev)/c;
        y_prev = y_curr;
        y_curr = y_next;
        if (y_next == e_k) 
            n = n + 1;
        end
        % gives empty plot 
        plot(x, y_curr);
    end   

end

3 个答案:

答案 0 :(得分:3)

Kedarp的回答显示了如何逐点更新绘图,但您也提到由于索引问题而无法存储值。

此方法还整理了您的代码,无需y_curry_nexty_prev,因此可能会更快一点:

function n = get_nodes(x_s, x_e, e_k)
    h = 10^-5;
    n = 0;
    x = x_s+0.1:h:x_e-0.1; % Set up x vector
    y = zeros(size(x));    % pre-allocate vector for y_curr values
    y(2) = 1;              % You previously called this y_curr, already y_prev = Y(1) = 0
    for ii = 3:numel(x)    % notice in particular that the loop starts from 3, for y(ii-2)
        a = 2 + (5/6)*forcing(x(ii), e_k)*h^2;
        b = 1 - (1/12)*forcing(x(ii)-h, e_k)*h^2;
        c = 1 - (1/12)*forcing(x(ii)+h, e_k)*h^2;
        % Assign next y value, swapping which value is current happens naturally
        y(ii) = (a * y(ii-1) + b * y(ii-2))/c;           
    end     
    n = sum(y == e_k);     % now we have y stored, we can get n outside the loop
    plot(x,y)              % can just plot all at once...
end

编辑:如果你更聪明,你也可以在a,b,c循环之外进行for计算!您为每forcing(x(ii), e_k)计算ii次3次,因为您每次都会执行3个相邻点。

如果您设置forcing以便它可以使用向量x,则可以调用f = forcing(x, e_k) 一次,然后您可以定义{{1 }},ab,只需在循环中迭代c即可。 这肯定会节省时间。

答案 1 :(得分:1)

如果你想在计算时进行绘图,你需要在循环中定义从前一点到当前点的线,并保持前一个底池。您可以将绘图线更改为:

    hold on
    plot([x-h x],[y_prev y_curr]);

答案 2 :(得分:1)

我建议设置绘图处理对象以便在循环中绘图,而不是每次都创建新绘图。例如,

x = 1:100;
% Initialise plot handle
h = plot(nan,nan);

for iter = 1:1e2
   y = rand + rand*x + rand*(x.^2 );
   % set appropriate values of handle
   set(h, {'XData','YData'}, {x, y});
   drawnow;
end

这样,plot句柄只创建一次,其属性在循环中设置。