Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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.

Réponse acceptée

Roger Stafford
Roger Stafford le 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 commentaire
Steve
Steve le 4 Nov 2013
Modifié(e) : Steve le 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

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 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.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by