【问题标题】:Simulate and plot with matlab用matlab模拟和绘图
【发布时间】:2017-10-02 01:09:42
【问题描述】:

我正在尝试模拟一些随机变量 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)

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

【问题讨论】:

  • 试试:N = 100; X = zeros(length(N)) for M = 1:N y_i = randi([-1 1], M, 1); X(M) = sum(y_i); end plot(1:N, X)

标签: matlab simulation


【解决方案1】:

似乎有人已经为您提供了正确的答案,但让我解释一下我将如何去做。你做错的唯一一件事是关于索引。试试这个。

    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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多