Clear Filters
Clear Filters

How to eliminate the for in the following function and make it vectorized, should be simple?

1 view (last 30 days)
Hello Experts,
I need to generate a sequence of integers X_i; i = 1:100000 within the interval 0 to 134455 using the recursion:
X_i+1 = 8121*X_i + 28411 mod 134456.
What I did is this:
X = zeros(100000,1);
i = 1;
X(1,1) = randi(134455);
for i=1:100000
X(i+1,1) = mod(8121*X(i,1) + 28411,28411);
end
I wanted to make it a bit more tricky and maybe eliminate the for loop. Please guide me how to do this quick and easy.

Accepted Answer

Roger Stafford
Roger Stafford on 3 Nov 2013
Your problem statement and your code are not in agreement. Presumably the line in the code's for-loop ought to be:
X(i+1,1) = mod(8121*X(i,1) + 28411,134456);
instead of what you have.
With the values you are using - 8121, 28411, and 134456 - this iteration will cycle through all possible 134,456 integers from 0 to 134455 in its particular order if you change the for-loop to:
for i = 1:134455
and on the next step it would return to the initial value again. This is true no matter what value, X(1), you start with. Different starting values will merely produce circularly shifted versions of one another.
I see no point in attempting to vectorize this code. It is already in a very simple and efficient form and takes only a few seconds to execute.
  1 Comment
Steve
Steve on 4 Nov 2013
Edited: Steve on 4 Nov 2013
Please correct me if I am mistaken:
% Initialization of 100000x1 vector
x = ones(100000,1);
% Generating pseudo-random integers vector using the rule:
% x(i+1) = a*x(i) mod n. a = 8121, n = 28411.
for i=1:100000
x(i+1,1) = mod(8121*x(i,1) + 28411,134456);
end

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 3 Nov 2013
X is a floating point number. To be sure you don't get bitten by this FAQ entry, create X as integer:
X = zeros(100000, 1, 'int32');
"A bit more tricky" and "quick and easy" seem like opposites. I think you've already made it as complicated as necessary since you could have just called randi() and get the whole sequence of random numbers in one single line of code.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!