# Generating random number between 1 to 10

54 visualizaciones (últimos 30 días)
Aftab Ahmed Khan el 1 de Jul. de 2014
Comentada: Souarv De el 8 de Oct. de 2021
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
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

dpb el 1 de Jul. de 2014
Editada: dpb el 1 de Jul. de 2014
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
##### 3 comentariosMostrar 1 comentario más antiguoOcultar 1 comentario más antiguo
Aftab Ahmed Khan el 1 de Jul. de 2014
Ok thanks, i solved it.
dpb el 1 de Jul. de 2014
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.
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.

Iniciar sesión para comentar.

### Más respuestas (3)

Jos (10584) el 2 de Jul. de 2014
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
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Souarv De el 8 de Oct. de 2021
That's nice.

Iniciar sesión para comentar.

Juan Gonzalez el 13 de Abr. de 2021
This is the easiest way
ceil(rand*10)
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
dpb el 13 de Abr. de 2021
Editada: dpb el 13 de Abr. de 2021
But won't follow the request of OP to have sampling without replacement so that none can be repeated in the 10 samples.

Iniciar sesión para comentar.

Elias Gule el 2 de Jul. de 2014
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
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by