使用matlab进行模拟和绘图

时间:2017-10-02 01:09:42

标签: matlab simulation

我试图模拟一些随机变量Y,使得P(Y = 1)= P(y = -1)= 0.5,并且X_n = Y_i的总和(i从1到n)。我想使用matlab来模拟X_n并将其绘制成不同的n,其中n = 1,2,3,... 100。这是我的matlab代码:

    N = 100;
for M = 1:N
    y_i = randi([-1 1], M, 1);
    X_n = sum(y_i);
end

plot(M, X_n)

但我的情节看起来像这样,有人可以帮我解决吗?我的代码有问题吗?谢谢。

enter image description here

1 个答案:

答案 0 :(得分:0)

似乎有人已经为你提供了正确的答案,但让我解释一下,我将如何解决这个问题。你唯一错的就是索引。试试这个。

    N = 100;                      % sets your maximum

for M = 1:N                       % loops from 1 - N
    y_i = randi([-1 1], M, 1);    % your formula
    X(M) = sum(y_i);              % stores your data in vectors with increasing index from 1 - 100
end

index = 1:N                       % generates a vector 1-100 to serve as indexes
plot(index, X)                    % plots each point of X a corresponding index