Hi everyone,
I want to generate a random number between 1 to 10 for 10 loop iteration, with this code section of mine but i want that each time it generate a different number. Forexample if 2 is generated for the 1st loop iteration, then for the rest of 9 iteration. It won't generate 2 again. Similarly for the rest of other numbers between 1 to 10.
for i=1:10
r = (b-a)*rand(1) + a
end

 Akzeptierte Antwort

dpb
dpb am 1 Jul. 2014
Bearbeitet: dpb am 1 Jul. 2014

0 Stimmen

That's "sampling w/o replacement". One relatively simple way--
N1=1; N2=10; % range desired
p=randperm(N1:N2);
for i=N1:N2
r=p(i);
...
ERRATA
As noted, in comment, forgot there isn't such a form for randperm. Seems like reasonable enhancement altho it's easy enough to scale externally, too.
Use
N=10; % range desired
p=randperm(N);
for i=1:N
instead.

3 Kommentare

Thank you for the response.
but this give me an error of this, Attempted to access p(2); index out of bounds because numel(p)=1.
a=1;
b=10; % range desired
p = randperm(a:b);
for i = a:b
r = p(i);
end
Aftab Ahmed Khan
Aftab Ahmed Khan am 1 Jul. 2014
Ok thanks, i solved it.
Ewww...mea culpa. I was thinking there was a vector version of inputs to randperm to move the range from the default 1:N to N1:N2 but there isn't. Was trying to generalize.
For your case, just use
N=10;
p=randperm(N);
for i=1:N
...
If you do need integers from other than 1:N, scale the resulting array as needed.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (3)

Jos (10584)
Jos (10584) am 2 Jul. 2014

2 Stimmen

In matlab you can directly loop over a vector (no need for indexing)
V = randperm(10) % example vector
for x = V
% x will iterate over the values of V
disp(x)
end
Juan Gonzalez
Juan Gonzalez am 13 Apr. 2021

1 Stimme

This is the easiest way
ceil(rand*10)

1 Kommentar

dpb
dpb am 13 Apr. 2021
Bearbeitet: dpb am 13 Apr. 2021
But won't follow the request of OP to have sampling without replacement so that none can be repeated in the 10 samples.

Melden Sie sich an, um zu kommentieren.

Elias Gule
Elias Gule am 2 Jul. 2014

0 Stimmen

N = 10; % size of the array
numArray = randperm(N); % array containing integers ranging from 1 : N
for k = numArray
%%perform some calculation/process
doSomething(k);
end

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by