# how to correct randsrc in matlab

58 views (last 30 days)
alex korhin on 19 Aug 2018
Commented: Steven Lord on 29 Jan 2021
Hi, we have an in-built function called 'randsrc(m,n)', where ideally it should generate an m-by-n matrix, each of whose entries independently takes the value -1 with probability 1/2, and 1 with probability 1/2.
Problem: I have used
X = [-5 -1 3 5 7];
pmf = [0.1 0.25 0.15 0.3 0.2] ;
out=randsrc(100, 1, [X; pmf] )
and im not getting a the rigth probability .how can i fix it
Steven Lord on 29 Jan 2021
Build a "deck of cards" and draw from it.
X = [-5 -1 3 5 7];
pmf = [0.1 0.25 0.15 0.3 0.2] ;
totalNumber = 100;
numberOfEach = round(pmf*totalNumber)
numberOfEach = 1×5
10 25 15 30 20
if sum(numberOfEach) ~= totalNumber
error("Unable to generate exactly " + totalNumber + ...
" elements from probability vector")
end
deck = repelem(X, numberOfEach);
shuffledDeck = deck(randperm(totalNumber));
% Show the shuffled deck
disp(reshape(shuffledDeck, 10, 10))
7 -1 3 7 -1 5 5 -1 5 5 7 7 -5 -1 3 5 3 -5 3 3 3 5 -1 7 3 -1 -1 5 -1 5 -5 7 5 5 3 5 5 5 -5 5 5 -1 -1 7 7 5 5 5 5 -1 -5 5 -1 -1 -1 7 -1 5 5 -1 -5 3 -5 3 3 -1 7 5 7 7 -1 5 3 7 5 7 -1 7 -5 -1 3 7 5 5 3 -1 3 5 7 -1 -1 -5 -1 5 7 5 7 -5 7 -1
% Check
fprintf("There should be " + numberOfEach(3) + " copies of " + X(3) + ...
" in the deck and there are " + nnz(deck == X(3)) + ".")
There should be 15 copies of 3 in the deck and there are 15.

Walter Roberson on 20 Aug 2018
N = 100;
X = [-5 -1 3 5 7];
pmf = [0.1 0.25 0.15 0.3 0.2];
%round() by itself could result in overallocation if you are not careful.
howmany = round(pmf * N); howmany(end) = N - sum(howmany(1:end-1));
[~, ~, bin] = histcounts(1:N,1+[0 cumsum(howmany)]);
bin = bin(randperm(length(bin))) .';
out = X(bin);
Walter Roberson on 20 Aug 2018
randperm uses rand() internally.

### Categories

Find more on Logical 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!