Sample row from array

How do I sample from a two dimensional array by row?

Is there a julia specific way and/or build-in function to do this?

I am only able to sample elements

using StatsBase

m = [1 2 3; 4 5 6; 7 8 9]
sample(m,3)

So I must use an intermediate step

using StatsBase
m = [1 2 3; 4 5 6; 7 8 9]
idx = sample(1:size(m,1),3)
m[idx,:]

Unfortunately, the solution proposed on stackoverflow does not work as there is no function indices

Thanks!

I am away from the computer, but can you try this?

using StatsBase
m = [1 2 3; 4 5 6; 7 8 9]
idx = sample(axes(m,1),3)
m[idx,:]

What’s wrong with that? It’s only one extra line.

You can also write m[sample(begin:end, 3), :].

2 Likes

Thanks, everybody.

@stevengj no, there is nothing wrong with that. I was just wondering if there is something like sample(m,3;axis=1)

1 Like