help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Extracting random elements from an array

 From: James Sherman Jr. Subject: Re: Extracting random elements from an array Date: Mon, 18 Apr 2011 00:39:53 -0400

On Mon, Apr 18, 2011 at 12:38 AM, James Sherman Jr. wrote:
On Mon, Apr 18, 2011 at 12:13 AM, shay wrote:
I have three arrays, a, b & c.
>I need to extract a random element from a or b and then 8 more random
elements from all 3.
>>then i need to create an array containing these elements which should be
easy enough for me to do.

# 8 random elements in array a
n = prod(size(a));
m = 8;
shuffle = randperm(n);
# to get m elements, just take the first m numbers of shuffle
random_elements = a(shuffle(1:m));

if you want to get a elements from either, a, b, or c, I'd just concatenate them, and randomly pick from the whole thing.  To pick one from either a or b, just concatenate a and b.

I'm assuming that you don't want replacement (no element picked twice).  If you want the chance for picking an element multiple times, replace the shuffle line with something like:
random_indices = round(rand(m, 1)*n+0.5);
random_elements = a(shuffle(1:m));

Hope this helps.

Copy and paste blunder, the last line should read:
random_elements = a(random_indices);

reply via email to

 [Prev in Thread] Current Thread [Next in Thread]