How can I get MATLAB to select a random variable from a set of variables?

I'm trying to write a program that generates a random combination based on variables. For example, the first set has variables A through D and a second set has variables E through H. I want to generate combinations from both sets like AE, DH, CF, etc.

 Accepted Answer

I don't know what AE etc. means. Do you mean to concatenate them, like [A, E]? If so try this:
% Assign 4 variables.
a=1;
b=2;
c=3;
d=4;
r1 = randi(4)
% Select one of them at random.
switch r1
case 1
out1 = a
case 2
out1 = b
case 3
out1 = c
otherwise
out1 = d
end
% Assign 4 variables.
e=11;
f=12;
g=13;
h=14;
% Select one of them at random.
r2 = randi(4)
switch r2
case 1
out2 = e
case 2
out2 = f
case 3
out2 = g
otherwise
out2 = h;
end
% Now make the concatenation
out = [out1, out2]

More Answers (1)

The functions I show there are for 6 sets, but otherwise the code is generalized -- notice there that the first thing I do is toss the values to select from into a cell array, so you can follow on from after that step if your values are already in a cell array.

Categories

Find more on Random Number Generation 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!