So, using Tim's suggestion this would be: # assume anything which isn't an array is scalar u2(x, Lbox) = x>Lbox/2 ? 0 : 0.5*(u2_0(x)+u2_0(Lbox-x))-u2_0(Lbox/2)
u2(x::AbstractArray, Lbox) = map( x->u2(x,Lbox), x) So, no code duplication. However, on the current release writing the second function with a loop will be more preformant (and no code duplication either). On Wed, 2016-02-10 at 13:21, Tim Holy <tim.h...@gmail.com> wrote: > I'm not quite sure if this is what you're asking, but if you want a scalar > function to work elementwise on an array, try `map`. > > --Tim > > On Wednesday, February 10, 2016 04:15:30 AM Ferran Mazzanti wrote: >> Thanks Mauro... >> >> using two methods was the first thing I thought, but I strongly dislike the >> idea because I'd have to maintain two different functions >> to do the same, which doubles the possibility of introducing bugs. I like >> the idea of keeping the main function simple and unique, >> so if I change something the changes apply to all calculations in the same >> way. >> >> Best regards, >> >> Ferran. >> >> On Wednesday, February 10, 2016 at 12:11:00 PM UTC+1, Mauro wrote: >> > Probably cleanest would be to make two methods, one for scalars, one for >> > arrays. For the array one just loop. >> > >> > This also works, but returns an array for scalar input (type inference >> > should work once wrapped in a function): >> > >> > julia> x = 5 >> > 5 >> > >> > julia> [ xi>5 ? 0:1 for xi in x] >> > >> > 1-element Array{Any,1}: >> > 1 >> > >> > julia> x = 1:10 >> > 1:10 >> > >> > julia> [ xi>5 ? 0:blah for xi in x] >> > >> > 10-element Array{Any,1}: >> > 1 >> > 1 >> > 1 >> > 1 >> > 1 >> > 0 >> > 0 >> > 0 >> > 0 >> > 0 >> > >> > On Wed, 2016-02-10 at 11:58, Ferran Mazzanti <ferran....@gmail.com >> > >> > <javascript:>> wrote: >> > > Hi folks, >> > > >> > > probably a stupid question but can't find the answer, so please help if >> > >> > you >> > >> > > can :) >> > > I would like to evaluate a if.. else.. statement on a whole array. >> > >> > Actually >> > >> > > it's a bit more complicated, as I have a function that >> > > previously was >> > > >> > > function u2(x) >> > > >> > > return 0.5*(u2_0(x)+u2_0(Lbox-x))-u2_0(Lbox/2) >> > > >> > > end; >> > > >> > > for some other defined function u2(x) and constant L_box. The thing is >> > >> > that >> > >> > > I could directly evaluate that on a scalar x and on an array. >> > > Now I have to change it and check if x is smaller than Lbox/2, returning >> > > the same as above if it is, or 0 otherwise. >> > > I tried something of the form >> > > >> > > function u2(x) >> > > >> > > return x.>Lbox/2 ? 0 : 0.5*(u2_0(x)+u2_0(Lbox-x))-u2_0(Lbox/2) >> > > >> > > end; >> > > >> > > but that complains when x is an array. What would be the easiest way to >> > > achieve this? It should work for both scalars and arrays... >> > > >> > > Best regards and thanks, >> > > >> > > Ferran.