If you are worried about maintaining two versions, that can be solved
simply:
function foo(x::Vector{bar})
#the main code of your function
end
function foo(x::bar)
foo([x])
end
Den onsdag den 10. februar 2016 kl. 13.15.30 UTC+1 skrev Ferran Mazzanti:
>
> 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 <[email protected]>
>> 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.
>>
>