how to correct randsrc in matlab
Show older comments
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
Walter Roberson
on 19 Aug 2018
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?
alex korhin
on 20 Aug 2018
Nguyen Tien Dat
on 29 Jan 2021
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)
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))
% Check
fprintf("There should be " + numberOfEach(3) + " copies of " + X(3) + ...
" in the deck and there are " + nnz(deck == X(3)) + ".")
Answers (1)
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);
3 Comments
Steven Lord
on 20 Aug 2018
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.
alex korhin
on 20 Aug 2018
Walter Roberson
on 20 Aug 2018
randperm uses rand() internally.
Categories
Find more on Communications Toolbox in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!