필터 지우기
필터 지우기

How to generate a random matrix with a constraint or step range ?

조회 수: 5 (최근 30일)
Varun Pai
Varun Pai 2020년 4월 23일
댓글: Varun Pai 2020년 4월 23일
I want to generate a Nx4 random matrix. In this matrix, each column is considered having different range and step. The random values should be only from these steps.
For e.g. 1st column 0:0.1:1
2nd column > 0:1:10
3rd column > 2:0.5:8
4th column > 0:-1:-10
I want to generate a random matrix of N=5. I should get a matrix with above conditions. Like this
[0 5 3.5 -5 ;
0.8 8 7 -3
0.2 0 2.5 -7
0.6 8 6.5 0
0.9 3 7.5 -9]
The N value could go to any size. Repeated values are permissible. I tried some random functions like randperm, randsample etc but I am not able to produce like this. Randperm is not allowing to produce repeated values.
How could I generate it ? Could you help with a code sample ?

채택된 답변

KSSV
KSSV 2020년 4월 23일
편집: KSSV 2020년 4월 23일
Read about randsample, randperms.
C1 = 0:0.1:1 ;
C2 = 0:1:10 ;
C3 = 2:0.5:8 ;
C4 = 0:-1:-10 ;
N = 5 ; M = 4 ;
C = zeros(N,M) ;
C(:,1) = randsample(C1',5) ;
C(:,2) = randsample(C2',5) ;
C(:,3) = randsample(C3',5) ;
C(:,4) = randsample(C4',5) ;
  댓글 수: 3
KSSV
KSSV 2020년 4월 23일
편집: KSSV 2020년 4월 23일
You split the big number into multiples and pick from each column.
You can use repmat on C1, repeat the values and pick them at once.
Varun Pai
Varun Pai 2020년 4월 23일
That's great... Thank you for the suggestion.
function ParameterSet = GenerateRandomSet(MinVal,MaxVal,StepVal,N)
% MinVal : 1 x M array of Lower limit
% MaxVal : 1 x M array of Upper limit
% StepVal : 1 x M array of Step values
% N : ParameterSet row size
% Usage eg. GenerateRandomSet([0 0 2 0],[1 10 8 -10],[0.1 1 0.5 -1],50)
rows = N;
cols = length(MinVal);
ParameterSet = zeros(rows,cols);
for c = 1:cols
ParamVectors = MinVal(c):StepVal(c):MaxVal(c);
repfactor = floor(N/length(ParamVectors)) + 1;
ParamVectors = repmat(ParamVectors,1,repfactor);
ParameterSet(:,c) = randsample(ParamVectors',N);
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

madhan ravi
madhan ravi 2020년 4월 23일
Hint example:
x = 1:10;
N = 5;
x(randi(numel(x),1,N))

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by