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 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!