【问题标题】:Extracting data from a plot within a for loop从 for 循环中的绘图中提取数据
【发布时间】:2015-12-15 03:16:34
【问题描述】:

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

对于每个 Qp 值,我有 100 个 PStoch 值,因为我为每个 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

剧情在这里:

感谢您的帮助。

【问题讨论】:

  • Qp 设为向量,将Pstoch 设为矩阵,并将所有内容索引到它们中,而不是标量。
  • 您能详细说明一下吗?我了解制作向量和矩阵,但不是“为所有内容编制索引”。
  • 其实你甚至不需要Qp,只要在情节中使用QpvecPstoch 多于 100 列,len 行,所以将其设为 zeros(len,100),然后像 Pstoch(k,i) 一样将元素放入其中,您只需计算 i,只需计算您的迭代次数while 循环。

标签: matlab for-loop data-acquisition


【解决方案1】:

我在下面的代码中添加了三行。这假设您说 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 目前无疑会警告您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2013-06-08
    • 2019-12-09
    • 2016-02-09
    • 1970-01-01
    相关资源
    最近更新 更多