Please help me in generating a random string(row vector) in which each element has a different upper bound.

4 vues (au cours des 30 derniers jours)
For example, I want to generate a row vector A randomly
A = [ 4 2 6 1 5 ];
Whose elements are bounded by an upper bound
UB = [ 5 4 6 3 5 ]
E.g. the first element of A can take any integer value between [0 – 5] and second element can take any integer value [0 – 4] and similarly other elements are bounded.
Now from this row vector 'A', N (length (A)), new vectors are to be generated. In each vector, an element of the vector A changes the value randomly within the upper bound and rest of the elements remains same. For example, for above vector A
A = [ 4 2 6 1 5 ];
New vectors are
A1 = [ 3 2 6 1 5 ];
A2 = [ 4 1 6 1 5 ];
A3 = [ 4 2 3 1 5 ];
A4 = [ 4 2 6 3 5 ];
A5 = [ 4 2 6 1 2 ];
Please help. Thanks in anticipation!

Réponse acceptée

Massimo Zanetti
Massimo Zanetti le 23 Fév 2017
Modifié(e) : Massimo Zanetti le 23 Fév 2017
The useful way is
U = [2,3,4,5,7];
A = arrayfun( @(x) randi([0,x]) , U )
but, if upper-bounds are 1-digit numbers, you can lighten the procedure by generating one random integer between 0 and N, where N is the number obtained by merging your 1-digit upper bounds. An example:
%your input
U = [5,4,6,8,6];
%merge digits
N = str2double(char(U+'0'))
%get random number between 0 and N
An = randi([0,N])
%get a vector of An digits
A = num2str(An)-'0'
N =
54686
An =
34015
A =
[3 4 0 1 5]
NOTES:
  1. this only works if upper-bounds are 1-digit numbers!
  2. you must treat appropriately leading zeros in A, e.g., if
A = [2,3,4]
you must get to
A = [0,0,2,3,4]

Plus de réponses (0)

Catégories

En savoir plus sur Random Number Generation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by