how to use the randi function to perform random numbers provided that no random number results are repeated or are not the same?

6 views (last 30 days)
i want to do random numbers
phi = 1: 4 looping using the randi function.
I want each iteration not to come out the same number
so
iteration 1
randi (phi) = 3
iteration 2
randi (phi) = 1
iteration 3
randi (phi) = 4
iteration 4
randi (phi) = 2
I don't use the randperm function because what I want the output of the random result is one number.
how is the solution?

Answers (1)

Walter Roberson
Walter Roberson on 3 Oct 2020
so_far = [];
for count = 1 : 4
trial = randi(4);
while ismember(trial, so_far)
trial = randi(4);
end
randi_phi(count) = trial;
do something with trial
end
However, there is seldom a good reason to do this. Instead do
randi_phi = randperm(4);
for count = 1 : 4
trial = randi_phi(count);
do something with trial
end
  3 Comments
Walter Roberson
Walter Roberson on 3 Oct 2020
There is another method:
available = 1:4;
for count = 1 : length(available)
used_idx = randi(length(available));
trial = available(used_idx);
available(used_idx) = [];
randi_phi(count) = trial;
do something with trial
end
Muhammad Sam'an
Muhammad Sam'an on 5 Oct 2020
let
c=[10 2 20 11
12 7 9 20
4 14 16 18 ];
s=[15
25
10 ];
d=[5 15 15 15 ];
[m,n]=size(c );
pop_size=25
gen_iter=100
phi=1:12
for ii=1:pop_size
randi_phi = randperm(length(phi ))
for count = 1 : length(phi )
count
k= randi_phi(count )
i=[1+mod((k-1),m )]
j=[1+mod((k-1),n )]
x(i,j)=min(s(i),d(j ))
s(i)= s(i)-x(i,j )
d(j)= d(j)-x(i,j )
end
end
I want to find x (i, j) until the loop pop_size = 25 but my math lab code results in x (i, j) = (m, n) = 0, even though if the loop uses length phi the value x (i, j) comes out or not zero. if anyone can help my mathlab code this. ? This I use a new genetic algorithm at the chromosome initialization stage

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!