从for循环中的绘图中提取数据

时间:2015-12-15 03:16:34

标签: matlab for-loop data-acquisition

在MATLAB中,我编写了随机模拟算法(Gillespie)用于简单的生灭过程,并在hold on循环中使用for得到了一个图。

我为每个PStoch值设置了100个Qp值,因为我为每个Qp值运行了100次模拟。在下面的图中很难看到这些值,因为它们都聚集在一起。

如何将图中的数据保存在矩阵中,以后我可以对它们进行一些计算?具体来说,我需要一个尺寸为100 x 100的矩阵,其中所有PStoch值都对应于每个Qp值。

我的代码如下:

rng('shuffle')

%% Pre-defined variables
Qpvec = logspace(-2,1,100);
len = length(Qpvec);
delta = 1e-3;
P0vec = Qpvec./delta;
V = [1,-1];
tmax = 10000;

%% Begin simulation
figure(1)
for k = 1:len
    t0 = 0;
    tspan = t0;
    Qp = Qpvec(k);
    P0 = P0vec(k);
    Pstoch = P0;
    while t0 < tmax && length(Pstoch) < 100
        a = [Qp, delta*P0];
        tau = -log(rand)/sum(a);
        t0 = t0 + tau;
        asum = cumsum(a)/sum(a);
        chosen_reaction = find(rand < asum,1);
        if chosen_reaction == 1;
            P0 = P0 + V(:,1);
        else
            P0 = P0 + V(:,2);
        end
        tspan = [tspan,t0];
        Pstoch = [Pstoch;P0];
    end
    plot(Qp,Pstoch)
    hold on
    axis([0 max(Qp) 0 max(Pstoch)])
end

情节在这里:enter image description here

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

我在下面的代码中添加了三行。这假设您说Pstoch总是有100个元素(或小于100)是正确的:

Pstoch_M = zeros(len, 100)

for

    k = 1:len
    t0 = 0;
    tspan = t0;
    Qp = Qpvec(k);
    P0 = P0vec(k);

    Pstoch = zeros(100,1);
    counter = 1;    

    Pstoch(1) = P0;
    while t0 < tmax && counter < 100 %// length(Pstoch) < 100
        a = [Qp, delta*P0];
        tau = -log(rand)/sum(a);
        t0 = t0 + tau;
        asum = cumsum(a)/sum(a);
        chosen_reaction = find(rand < asum,1);
        if chosen_reaction == 1;
            P0 = P0 + V(:,1);
        else
            P0 = P0 + V(:,2);
        end
        counter = counter + 1;
        tspan = [tspan,t0];
        Pstoch(counter) P0;;
    end

    Pstock_M(:,k) = Pstoch;

    plot(Qp,Pstoch)
    hold on
    axis([0 max(Qp) 0 max(Pstoch)])
end

请注意,为Pstoch添加的预分配应该会使您的代码更快。你应该为tspan做同样的事情。 MATLAB中循环内部变量的增长是非常低效的,因为m-lint无疑正在警告你。

相关问题