Randomize / Shuffle function with order (no subsequent repetition) constraint
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello, I am using MATLAB 2016b and I am looking to write a matlab function that randomizes / shuffles a matrix with some constraints.
Specifically, the input for this function would be a 10*1 matrix with the following content: [1;2;3;4;5;6;7;8;9;10]. Next I would like to have a variable (lets call it X) that specifies the amount of repetitions and therefore indicates the dimensions of the output matrix (see further for more clarification)
The wanted output is a X*1 matrix, with X being a multiple of 10 (e.g., 20*1, 30*1, 40*1, etc), based on the X variable that I discussed previously.
The goal is to randomize and shuffle the input matrix, and save this output to another matrix. The output matrix needs to satisfy the following constraints: - Every number from the input matrix needs to be equally present in the output matrix. So for example, if the output matrix is specified to be 20*1, every number needs to be present twice in the output matrix, and so on. - No more than two consecutive repeats from the same number are allowed in the output matrix. Thus, for example 2;2;3 is allowed, but not 2;2;2
I hope someone can and wants to help me in this quest. Thanks in advance
댓글 수: 0
채택된 답변
Guillaume
2018년 7월 30일
Your requirements seem fairly simple. The only difficult one is the requirement that there be no more than two identical consecutive numbers. I' d just keep generating permutations until that's the case:
%inputs
v = 1:10; %input vector of different numbers
x = 5; %number of repetitions
out = repelem(v, x);
out = out(randperm(numel(out))); %1st try
while ~isempty(strfind(diff(out), [0 0])) %diff(out) will have at least two consecutive 0 if there are 3 or more identical consecutive numbers
out = out(randperm(numel(out))); %try again
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
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!