How to eliminate the for in the following function and make it vectorized, should be simple?
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
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.
More Answers (1)
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.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!