matlab:粒子状态模拟

标签 matlab random distribution simulation poisson

假设我想模拟一个粒子状态,在给定帧中可以是正常状态 (0) 或激发状态 (1)。粒子在 f % 的时间内处于激发态。如果粒子处于激发态,它会持续〜L帧(具有泊松分布)。我想模拟 N 个时间点的状态。因此输入例如:

N = 1000;
f = 0.3;
L = 5;

结果会是这样的

state(1:N) = [0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 ... and so on]

sum(state)/N 接近 0.3

如何做到这一点? 谢谢!

最佳答案

%% parameters
f = 0.3; % probability of state 1
L1 = 5;  % average time in state 1
N = 1e4;
s0 = 1; % init. state
%% run simulation
L0 = L1 * (1 / f - 1); % average time state 0 lasts
p01 = 1 / L0; % probability to switch from 0 to 1
p10 = 1 / L1; % probability to switch from 1 to 0
p00 = 1 - p01;
p11 = 1 - p10;
sm = [p00, p01; p10, p11];  % build stochastic matrix (state machine)
bins = [0, 1]; % possible states
states = zeros(N, 1);
assert(all(sum(sm, 2) == 1), 'not a stochastic matrix');
smc = cumsum(sm, 2); % cummulative matrix
xi = find(bins == s0);
for k = 1 : N
    yi = find(smc(xi, :) > rand, 1, 'first');
    states(k) = bins(yi);
    xi = yi;
end
%% check result
ds = [states(1); diff(states)];
idx_begin = find(ds == 1 & states == 1);
idx_end = find(ds == -1 & states == 0);
if idx_end(end) < idx_begin(end)
    idx_end = [idx_end; N + 1];
end
df = idx_end - idx_begin;
fprintf('prob(state = 1) = %g; avg. time(state = 1) = %g\n', sum(states) / N, mean(df));

关于matlab:粒子状态模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9858775/

相关文章:

C++随机数总是相同的

python - 分布的迭代排列

Matlab 柯尔莫哥洛夫-斯米尔诺夫检验

python - 如何在 python 中创建一个加密安全的随机数?

algorithm - 如何获得穿过正方形的线段的长度?

c++ - 为什么这个随机数生成器不是线程安全的?

python - scipy.stats.johnsonsu 中的 a 和 b 参数是什么?

java - 如何在 Java 中转移分布中的数据

matlab - 如何在matlab中找到与2行匹配的矩阵列?

matlab - 两条垂直线之间的阴影区域