Is there a way to De-Broadcast?

I have come across cases of functions (e.g. the functions in Splines2, and elsewhere) where vectors are required as inputs, and where these same functions fail for scalar input (where conversion to/from 1-dim vector is required)

Short of implementing a script for the special case of isa( ,Number)==true (converting to 1-dim vector, evaluating, and then converting back to scalar) is there a more elegant way to implement this ‘De-Broadcasting’?

Thanks for any help

I think what you want to do can be achieved by overloading the function via Multiple Dispatch. That is, implement a method of the function that takes a scalar as an input and makes the transformation to a vector so it then can be used by the method that only accepts a vector as input.

As a silly example, say you have a function that adds all the components of a vector. If you pass a scalar to that function, since there is nothing to sum, you expect the function to return that scalar. Therefore, we could have

sum_vec(x::AbstractVector) = sum(x) # This would throw an error for an scalar
sum_vec(x::Number) = sum_vec([x,]) # This works for scalars

As you can see, with the second method definition I insert the scalar into a 1 dimensional vector with 1 element which executes the first method definition of the function sum_vec.

just wrap your input in []?

The preferred way to not broadcast an input is to wrap it in an iterable. The common choices are Ref(x), [x], (x,). For example, in.(1:4,Ref(3:6)) is comparable to [in(z,3:6) for z in 1:4].

1 Like

Hi All,
Thanks - I think I will go with the multiple dispatch solution [ I was wondering if there were an
easier way.]
The tricky part is that the function is going to be called by a routine that I have no control over.

Thanks again