Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random string from alphabet with specific probabilities (issue with randsrc)

Tags:

matlab

So I am familiar with randsrc and that I can create from a random alphabet of integers with given probabilities. So lets say I have this alphabet

alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
prob=[0.08167 0.01492 0.02782 0.04254 0.12702 0.02228 0.02015 0.06094 0.06966 0.00153 0.00772 0.04025 0.02406 0.06749 0.07507 0.01929 0.00095 0.05987 0.06327 0.09056 0.02758 0.00978 0.02360 0.00150 0.01974 0.00074];

Notice: alphabet is a cell with 1x26 dimensions and prob is 1x26 double array.

I can create a random string like this

s = 'abcdefghijklmnopqrstuvwxyz';
%find number of random characters to choose from
numRands = length(s); 
%specify length of random string to generate
sLength = 10;
%generate random string
randString = s(ceil(rand(1,sLength)*numRands));

The problem with this way is that I can't figure out a way to take the probabilities in to account. So what I have been trying to do is:

randomString =randsrc(10,1,[alphabet; prob]);

But this gets displayed in console:

Error using vertcat 
Dimensions of arrays being concatenated are not consistent. 
Consider converting input arrays to the same type before concatenating.

Error in test (line 8) 
randomString = randsrc(10,1,[alphabet; prob]);

In this if I do:

alphabet = [097:122];

the randsrc will work.

But what ever I try I can't give the randsrc character alphabet. The reason I want to give the randsrc character alphabet is because my alphabet can be a lot more complicated that the first one, like this:

alphabet = {'aa','ab','ac'...'az','ba','bb','bc'...);

Is there anyway that I could make the randsrc get character alphabet and not integer. Or should I try to create my own function to do this?

Thanks in advance

like image 504
Gerasimos Ragavanis Avatar asked Oct 16 '22 08:10

Gerasimos Ragavanis


1 Answers

You can use randsrc to generate random indices into alphabet:

indices = randsrc(10,1,[1:numel(alphabet); prob]);
randomString = [alphabet{indices}];
like image 64
Cris Luengo Avatar answered Oct 21 '22 09:10

Cris Luengo