Reputation: 6395
Suppose I want to write a dynamic function that gets an object subtype of AbstractMatrix
and shuffles the values along a specified dimension. Surely there can be various approaches and ways to do this, but suppose the following way:
import Random.shuffle
function shuffle(data::AbstractMatrix; dims=1)
n = size(data, dims)
shuffled_idx = shuffle(1:n)
data[shuffled_idx, :] #This line is wrong. It's not dynamic
A wrong way is to use several (actually indefinite) if-else statements like if dims==1
do... if dims==2
do. But it isn't the way to do these kinds of things. I could write data::AbstractArray
then the input could have various dimensions. So this came to my mind that this can be possible if I can do something like getindex(data, [idxs]; dims)
. But I checked for the dims
keyword argument (or even positional one) in the dispatches of getindex
, but there isn't such a definition. So how can I get values by specified indexes and along a dim
?
Upvotes: 0
Views: 278
Reputation: 12664
You are looking for selectdim
:
help?> selectdim
search: selectdim
selectdim(A, d::Integer, i)
Return a view of all the data of A where the index for dimension d equals i.
Equivalent to view(A,:,:,...,i,:,:,...) where i is in position d.
Here's a code example:
function myshuffle(data::AbstractMatrix; dim=1)
inds = shuffle(axes(data, dim))
return selectdim(data, dim, inds)
end
Make sure not to use 1:n
as indices for AbstractArray
s, as they may have non-standard indices. Use axes
instead.
BTW, selectdim
apparently returns a view, so you may or may not need to use collect
on it.
Upvotes: 4