how to correct randsrc in matlab

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
Please help me in finding out the solution for this.

4 Comments

What difficulty are you observing?
When I test, I see the expected fractions of symbols, to within statistical bounds (e.g., my test was slightly low on 3 and slightly high on 7)
Are you wanting to produce results with exactly the given fractions? So for 0.1 you would want exactly 100*0.1 = 10 copies of -5, exactly 25 copies of -1, exactly 15 copies of 3, and so on?
i want the exactly probability that was asking
Hello Alex, I am facing the same issue with you when using this algorithm. Have you figured out how to resolve it by this algorithm or you tried another one?
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.

Sign in to comment.

Answers (1)

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);

3 Comments

Once you've computed howmany, you could use repelem instead of histcounts to create the sorted vector of replicates of elements of X. Then you just need to shuffle them using randperm.
i need random numbers
randperm uses rand() internally.

Sign in to comment.

Categories

Find more on Communications Toolbox in Help Center and File Exchange

Tags

Asked:

on 19 Aug 2018

Commented:

on 29 Jan 2021

Community Treasure Hunt

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

Start Hunting!