用matlab模拟和绘图
Simulate and plot with matlab
我正在尝试模拟一些随机变量 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; % 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
我正在尝试模拟一些随机变量 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; % 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