How to create random matrix with specified step in interval [a, b]
Mostrar comentarios más antiguos
Hello everyone. I want to create a matrix with size (m×n) and I want its entities be between 5 and 34 (or in interval [5,34]) with a step of 3. Which means it's only allowed to have 5, 8, 11, 14, ... . How can I create this matrix?
Respuesta aceptada
Más respuestas (3)
John D'Errico
el 22 de Mayo de 2022
Editada: John D'Errico
el 22 de Mayo de 2022
You can also use indexing. The idea is to generate random indexes.
ValidRandomSet = 5:3:34
m = 7;
n = 6;
ind = randi(numel(ValidRandomSet),[m,n])
X = ValidRandomSet(ind)
The virtue of such a scheme is it works for any target set of numbers.
1 comentario
Reza Lashani
el 23 de Mayo de 2022
Editada: Reza Lashani
el 23 de Mayo de 2022
generate a matrix with random integer values using randi. The spacing will be 1, you can then multiply the values by 3 to get spacing of 3. then shift your values towards your interval by addition
randi(10, 20,30)*3+2
max value will be 32 and minimum value 5
1 comentario
Reza Lashani
el 22 de Mayo de 2022
Editada: Reza Lashani
el 22 de Mayo de 2022
Image Analyst
el 22 de Mayo de 2022
Here's another way. You can create your random numbers as floating point then use discretize them into numbers in the set you specify:
m = 6
n = 18
% Get the random numbers
r = 5 + (35-5) * rand(m, n)
% Discretize into nearest integer that is in the set
% [5 8 11 14 17 20 23 26 29 32]
edges = 5:3:35
values = edges(1:end-1)
r2 = discretize(r, edges, values)
1 comentario
Reza Lashani
el 22 de Mayo de 2022
Categorías
Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!