How to create random matrix with specified step in interval [a, b]
조회 수: 23 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Voss
2022년 5월 22일
편집: Voss
2022년 5월 22일
a = 5;
b = 34;
step = 3;
offset = 2;
n_levels = 1+floor((b-a)/step)
% for your reference, showing the min and max
% random values that will be generated:
offset + step*[1 n_levels]
% required size of resulting random matrix:
m = 10;
n = 12;
% generate the matrix using randi,
% [1 n_levels] maps to [5 32]
result = offset + step*randi([1 n_levels],m,n)
댓글 수: 4
추가 답변 (3개)
John D'Errico
2022년 5월 22일
편집: John D'Errico
2022년 5월 22일
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.
Image Analyst
2022년 5월 22일
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)
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!