Function that produce an uniform random numbers for loop error

조회 수: 4 (최근 30일)
Faisal Al-Wazir
Faisal Al-Wazir 2022년 10월 14일
댓글: Faisal Al-Wazir 2022년 10월 14일
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

채택된 답변

KSSV
KSSV 2022년 10월 14일
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
Faisal Al-Wazir
Faisal Al-Wazir 2022년 10월 14일
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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by