efsee
efsee

Reputation: 629

Simulate and plot with matlab

I'm trying to simulate some random variables Y such that P(Y=1)=P(y=-1)=0.5, and X_n = sum of Y_i (i from 1 to n). I want to use matlab to simulate X_n and plot it versus different n's, where n = 1,2,3,...100. Here is my matlab code:

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

plot(M, X_n)

But my plot looks like this, can someone help me fix it? Is there something wrong with my code? Thank you.

enter image description here

Upvotes: 0

Views: 115

Answers (1)

Community
Community

Reputation: 175

Seems like somebody provided you with the right answer already but let me explain and how i would go about it. The only thing you're doing wrong is about the indexing. Try this.

    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 

Upvotes: 0

Related Questions