julesjanker
julesjanker

Reputation: 857

Matlab for loop - How to index?

I'm pretty rusty with Matlab programming and I'm stuck writing a for loop. I want to generate n random numbers using the formula x(i+1)=mod(a*x(i), m);

What I have is

for i=1:n
    x(i+1)=mod(a*x(i),m);
end

What I don't know, is

Upvotes: 0

Views: 67

Answers (1)

horchler
horchler

Reputation: 18484

You should preallocate x for a case like this. Given your for loop, the minimum index is 1 and maximum index is n+1 so x needs to be a vector with n+1 elements. You could use zeros, for example:

x = zeros(n+1,1); % An n+1 by 1 column vector

It looks like you should also set the value of x(1) to some kind of initial value too. Your for loop is effectively a recurrence relation where the i+1-th value of x depends on the i-th value.

Upvotes: 1

Related Questions