Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

matlab - Generate numbers randomly from a set?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...