Function that produce an uniform random numbers for loop error

4 visualizaciones (últimos 30 días)
Hi i'm having an issue in my for loop
i',m trying to make a function that produce an uniform random numbers but no matter what i adjust i keep getting the same error
clear
clc
%N=input('sequence_length')
N=5000
N = 5000
MinSec = fix(clock);
seed = 100*MinSec(5) + MinSec(6);
Urand = myrandi(seed,N);
la = 65539
P = 2.1475e+09
Index exceeds the number of array elements. Index must not exceed 1.

Error in solution>myrandi (line 33)
Urand(i)= mod(la*seed(i-1),P);
%b
%Y=ones(size(Urand));
subplot(2,1,1)
hist(Urand)
%% Task 1: : the Linear Congruential Generator (LCG)
v = rand(1,N);
%u=u./max(u);
subplot(3,2,2);
hist(v,100);
title(subplot(2,1,2),'Uniform random: rand()');
%Function that produce an uniform random numbers
%Using the technic of LCG r(k) = [lambda*r(k-1)]modulo(P)
function Urand = myrandi(seed,sequence_length)
la=65539
N=sequence_length;
P=2^31
%change N accordingly
%part a
Urand=zeros(1,N);
Urand(1)=seed;
for i=2:N
Urand(i)= mod(la*seed(i-1),P);
end
Urand=Urand/65539;
%printing genetrated vector, after dividing by 6655
if N<=50 %will print numbers only
if N<=50
disp(['for N = ',num2str(N)])
disp(Urand)
end
end
end%function myrand

Respuesta aceptada

KSSV
KSSV el 14 de Oct. de 2022
This line:
Urand(i)= mod(la*seed(i-1),P);
Your seed is a scalar, it has sinlge value. You are trying to extract more number by indexing it and treating it as a vector. This is the error.
Do you mean to use:
Urand(i)= mod(la*seed*(i-1),P);
  3 comentarios
Faisal Al-Wazir
Faisal Al-Wazir el 14 de Oct. de 2022
yes now it works
clear
clc
%N=input('sequence_length')
N=5000
N = 5000
MinSec = fix(clock);
seed = 100*MinSec(5) + MinSec(6);
Urand = myrandi(seed,N);
la = 65539
P = 2.1475e+09
Urand = 1×5000
0 0.0929 0.1859 0.2788 0.3717 0.4647 0.5576 0.6505 0.7434 0.8364 0.9293 0.0222 0.1152 0.2081 0.3010 0.3940 0.4869 0.5798 0.6727 0.7657 0.8586 0.9515 0.0445 0.1374 0.2303 0.3233 0.4162 0.5091 0.6020 0.6950
%b
%Y=ones(size(Urand));
subplot(3,2,1)
hist(Urand)
%% Task 1: : the Linear Congruential Generator (LCG)
v = rand(1,N);
%u=u./max(u);
subplot(3,2,2);
hist(v,100);
title(subplot(3,2,2),'Uniform random: rand()');
%Function that produce an uniform random numbers
%Using the technic of LCG r(k) = [lambda*r(k-1)]modulo(P)
function Urand = myrandi(seed,sequence_length)
la=65539
N=sequence_length;
P=2^31
%change N accordingly
%part a
Urand=zeros(1,N);
seed(1)=seed;
for i=2:N
Urand(i)= mod((la*seed*(i-1)),P);
end
Urand = Urand./(P-1)
end%function myrand

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by