help with @generated function call please?

67 views
Skip to first unread message

Florian Oswald

unread,
Oct 14, 2016, 11:51:13 AM10/14/16
to julia-users
hi all, 

I want to evaluate a function at each index of an array. There is a N dimensional function, and I want to map it onto an N-dimensional array:

fpoly(x::Array{Real,5}) = x[1] + x[2]^2 + x[3] + x[4]^2 + x[5] 

want to do 

a = rand(2,2,2,2,2);
b = similar(a)

for i1 in indices(a,1)
for i2 in indices(a,2)
...
b[i1,i2,i3,i4,i5] = fpoly(a[i1,i2,i3,i4,i5])
end
end...

I tried:
# actually want to do it inplace
@generated function set_poly!{T,N}(a::Array{T,N})
quote
@nloops $N i a begin
@nref $N a i = @ncall $N fpoly i->a[i]
end
end
end

but that fails. I dont get further than:

macroexpand(:(@nloops 3 j a begin
        x = @ncall 3 fpoly i->a[j]
        end))

quote  # cartesian.jl, line 62:

    for j_3 = indices(a,3) # cartesian.jl, line 63:

        nothing # cartesian.jl, line 64:

        begin  # cartesian.jl, line 62:

            for j_2 = indices(a,2) # cartesian.jl, line 63:

                nothing # cartesian.jl, line 64:

                begin  # cartesian.jl, line 62:

                    for j_1 = indices(a,1) # cartesian.jl, line 63:

                        nothing # cartesian.jl, line 64:

                        begin  # REPL[145], line 2:

                            x = fpoly(a[j],a[j],a[j])

                        end # cartesian.jl, line 65:

                        nothing

                    end

                end # cartesian.jl, line 65:

                nothing

            end

        end # cartesian.jl, line 65:

        nothing

    end

end




which is a start but how can I get the LHS right the indices of a right?



Erik Schnetter

unread,
Oct 15, 2016, 2:58:09 PM10/15/16
to julia...@googlegroups.com
A generated function is only useful if you perform a non-trivial calculation based on the argument types. You don't do that here, so I wonder whether simply using the Cartesian indexing macros by themselves would be sufficient.

Note also that you don't need to write `$N` in your code; using `N` directly has the same effect here.

I'm not saying that generated functions should be avoided at all costs, but if it isn't necessary here you might as well skip the associated complications.

-erik

Florian Oswald

unread,
Oct 15, 2016, 3:37:54 PM10/15/16
to julia...@googlegroups.com
Yes I think you are right about that. Using a comprehension is just as good for my case. But part of me would like to just finally understand that part of Julia! Ok will have to wait for the next opportunity. :-)

Thanks anyway.
Florian
Reply all
Reply to author
Forward
0 new messages