MATLAB: Randomly select values from a vector that yield a target mean

known meanknown sumrandom selectiontarget mean

I have a specific list of values, which can be arrayed in a vector: AR = [-.5, -.3, -.1, 0, .1, .3, .5] (note that it is not important for the values to be arranged in a vector necessarily)
I want to specify a target mean. E.g.: TM = -.1
Then, I want ML to randomly select any N values (with replacement) from vector AR, as long as those N values yield the target mean. For example,
AR = [-.5, -.3, -.1, 0, .1, .3, .5] TM = -.1 N = 4
*magic code goes here, and ML gives:
Output = [-.3, .1, -.5, .3]
N randomly selected values from a given set with a mean of TM. Any ideas how to achieve this?

Best Answer

nAR = length(AR);
[IDX{1:N}] = ndgrid(1:nAR);
IDXmat = cell2mat(cellfun(@(M) M(:), IDX, 'uniform', 0));
line_totals = sum(AR(IDXmat), 2);
mask = ismembertol(line_totals, TM);
matchingIDX = IDXmat(mask,:);
randchoice = randi(size(matchingIDX,1));
rand_ARentries = matchingIDX(randchoice, :);
You indicate that AR is constant. The IDXmat and line_totals can be pre-calculated.
The mask and matchingIDX can only be calculated once TM is known.
Once the combinations that match the required total are known, then one of them is chosen at random. If you are doing a number of trials with the same AR and same TM, then you only have to do the randchoice and rand_ARentries once per trial. If you want T random trials then
randchoices = randi(size(matchingIDX,1), T, 1);
rand_ARentries = matchingIDX(randchoices, :);
will select all T of them simultaneously.
If length(AR) is high then this code can have heavy memory use. But once everything is set up, the cost of generating a new random combination is quite small.