Generate numbers randomly from a set?

2019-02-27 13:32发布

问题:

In MATLAB, I have a set of P numbers. I would like to generate a random array of size N from this set.

For the sake of example, let say I have the set {1, 4}. Let say I would like to generate an array of size 5 (e.g., [1 1 4 1 4]).

What I did is this: I generated the following array using randi.

N = 5;
v = randi([1 4],[1 N]);

The problem is that I got a random array which contains values in 1:4 and not in {1, 4}. I can simply do this but I need a better way.

for i = 1:length(v)
    if v(i) ~= 1 || v(i) ~= 4
       v(i) = 1; % or v(i) = 4
    end
end

I think I am missing a simple hint here.

回答1:

You should use datasample,

y = datasample(data,k) returns k observations sampled uniformly at random, with replacement, from the data in data.

a = [1,4];
datasample(a,5)

Depending on the usage, you might consider using,

datasample(unique(a),5)


回答2:

If you don't have the Statistics Toolbox (which contains the datasample function), you can use randi:

N = 5; %// desired number of samples
data = [1 4]; %// data values
sample = data(randi(numel(data),1,N));

And if you use a very old version of Matlab that doesn't have randi, you can employ rand:

sample = data(ceil(numel(data)*rand(1,N)));


标签: matlab random