-2

I wanted to create a set of random numbers. I used the following code:

for i = 1:n
 for j = 1:n
   Sc{i,j} = sort((randperm(m,randi(m)))); 
end;
end;

This creates a cell array containing a set of random integers from 1 to 5. example Sc{1,1} = [1,3,4] I think, randi function uses uniform distribution. I want to control size of the set with some probabilty. For example I want my set to contain all 5 elements (that is of size 5) with a probability of .5 and and a set with 4, 3, 2,1 elements with probability .1 each. I don't know how to code it in matlab. Please help. I am fairly new to this software

abc
  • 1
  • 3
  • Your description is strange. In any way I could sum up the probabilities, I don't end with 1. – Daniel Dec 16 '13 at 21:49
  • do you know how to code it in a different language? to me this doesn't seem like a "matlab" question, but rather concerning the algorithm/method... – sebastian Dec 17 '13 at 08:27

1 Answers1

0

This should do the trick. Basically what you need to do, since there is really no straight fotward way of defining a custom weighted distribution, you can simply create an array that has the higher weighted elements in it more often, and then uniformly sample that array. So if some element has a probability of 0.5 then half the elements in your created array will be that value with probability of 0.5. Then, as said, simply use randi (with the whole array length) to select an index from that array, which will follow your custom distribution.

See code below

sizes = [1,2,3,4,5];
probs = [0.125,0.125,0.125,0.125,0.5];

% some initial sanity checks.
assert(numel(sizes) == numel(probs),'probability must be defined for each size')
assert(sum(probs)==1,'Probabilities must sum to 1')

numEach = round((probs/min(probs)));
weightedSizes = zeros(1,sum(numEach));    

start = 1;
for i = 1:numel(sizes)
    weightedSizes(start:start+numEach(i)-1) = sizes(i);
    start = start+numEach(i);
end

holder = cell(1,10);
for i = 1:10
    randSize = weightedSizes(randi(numel(weightedSizes)));
    holder{i} = randperm(randSize);
end

Note, be very careful using this method if you have something with a very small probability as it will create a very large matrix. This is because it assumes that the element with the smallest probability only appears once. There will be as many elements as 1/min(probability)

MZimmerman6
  • 8,445
  • 10
  • 40
  • 70
  • while my solution does work, I would actually suggest using the solution in the question this is duplicating. The one that Eitan T provided as it is much simpler, does not have the same limitations mine does, and run a lot faster. – MZimmerman6 Dec 19 '13 at 16:07