Has anyone ever needed to “shuffle” an NArray? I can certainly convert
it to an array and do the sort_by {rand} idiom, and then convert it
back. I currently:
na.size.times do
p1,p2 = rand(na.size),rand(na.size)
na[p1],na[p2] = na[p2],na[p1]
end
which works, but I wondering if anyone knew a better way.
Thanks
pth
On Thu, 7 Sep 2006, Patrick H. wrote:
Thanks
pth
if your na is not huge you might use:
harp:~ > cat a.rb
require 'narray'
na = NArray.int(3,2).indgen!
p na
idx = NArray.to_na Array.new(na.size){|i| i}.sort_by{ rand }
na[] = na[idx].reshape *na.shape
p na
harp:~ > ruby a.rb
NArray.int(3,2):
[ [ 0, 1, 2 ],
[ 3, 4, 5 ] ]
NArray.int(3,2):
[ [ 0, 3, 1 ],
[ 2, 4, 5 ] ]
which at least does it in one hit at the cost of space.
-a
“Patrick H.” [email protected] writes:
Has anyone ever needed to “shuffle” an NArray? I can certainly convert
it to an array and do the sort_by {rand} idiom, and then convert it
back. I currently:
What about:
shuffled = orig[NArray.float(*orig.shape).random!.sort_index]
On 9/6/06, Daniel M. [email protected] wrote:
–
s=%q( Daniel M. – [email protected]
puts “s=%q(#{s})”,s.map{|i|i}[1] )
puts “s=%q(#{s})”,s.map{|i|i}[1]
Thanks Daniel, that is perfect – I did not know you could index an NA
with an Array that way – its perfect for my needs (plus it keeps the
type of the Array).
pth