Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Dyadic mapslices with broadcasting #13317

Closed
wants to merge 1 commit into from

Conversation

mschauer
Copy link
Contributor

An open issue is to make mapslices accept two inputs and allow broadcasting. See #10928, #5140. There are aspects of the interface of mapslices which make straight generalization difficult. The result of the provided function applied to the slices is arranged along the unsliced dimensions, so for example

julia> mapslices(mean, rand(3,3), 2)
3x1 Array{Float64,2}:
 0.648857
 0.560829
 0.256913

julia> mapslices(mean, rand(3,3), 1)
1x5 Array{Float64,2}:
 0.518943  0.615732  0.471542  0.475519  0.557684

Further the result of f has to fit dimensionally into the slices, so that the resulting array has the same number of dimensions as the original. This behaviour does not generalize well to two arguments (what should the shape of mapslices(f, A, Adims, B, Bdims) be?).

The function mapranked(f, A, r, B, s) here follows APL and J and applies f only to the leading subarrays of given rank: For example, if r is 2 and A is 4-dimensional and s is 1 and B is 3-dimensional, then f is called on (A[:,:,i,j], B[:, i,j]) for all i and j. The results are concatenated along the remaining dimensions. The function broadcasts the arguments to a common size by expanding singleton dimensions. This more restrictive API makes the function conceptually much simpler. While it is meant to generalize mapslices to the dyadic case, to prevent confusion it should perhaps have a different name. Here I went with mapranked following the notion of changing the rank of a function/verb in APL (other suggestions?).

Some usage:

# Matrix from vector of vectors
mapranked(identity,[rand(5) for i in 1:10],0)

# Punnett square
cross(a,b) = string(a[1],b[1],a[2],b[2])
mapranked(cross, ["RA", "Ra", "rA", "ra"]',0,["RA", "Ra", "rA", "ra"],0 )

# Kronecker array
A = rand(3,3)
kron(A,A)[(2-1)*3+2,(2-1)*3+2] ==  mapranked(*, A, 0, A, 2)[2,2,2,2]

# selfclassify and memoize
v = rand(1:4, 10)
A = mapranked(.==, v, 1, unique(v), 0)

f(x) = begin sleep(.2*length(x)); x.*x end # time consuming computation ^^
sum(A.*f(unique(v))',2) # == f(v)

Ping @andreasnoack

@mschauer
Copy link
Contributor Author

This can be done in a much nicer way with shaped iterators and collect.

@mschauer mschauer closed this Feb 17, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant