How to fill larger array with the values of another array randomized?

6 views (last 30 days)
Hello,
E.g. I got an 'X' array with [1 2 3 4] and want to fill an 'Y' array which is length 8. The restrictions are:
- All values of 'X' array must be in the 'Y' array at least once.
- The values of 'X' are picked random and put in the 'Y' array.
An example of array 'Y' = [1 4 3 1 4 2 1 1].
Is there any function in Matlab which can accomplish this?
Thanks for the help!

Accepted Answer

Guillaume
Guillaume on 8 Oct 2015
I don't think there's anything built-in but it's trivial to write:
function filledarray = randfill(x, n)
%RANDFILL fill an array of size n with elements of x.
%Each element of x is guaranteed to be present at least once
%prerequisite: n >= numel(x)
%x: input vector to be shuffled
%n: size of output vector
assert(n >= numel(x), 'n must be at least the size of x');
indices = [1:numel(x), randi([1 numel(x)], 1, n-numel(x))]; %create list of indices 1-numel(x) + random indices
y = x(indices(randperm(n))); %and shuffle the whole lot.
end

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!