Borrar filtros
Borrar filtros

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

1 visualización (últimos 30 días)
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.

Respuesta aceptada

Roger Stafford
Roger Stafford el 3 de Nov. de 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 comentario
Steve
Steve el 4 de Nov. de 2013
Editada: Steve el 4 de Nov. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 3 de Nov. de 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.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by