I don't know of any way to accomplish what you want with a single method 
signature. I don't see how Union can help you, because you would not be 
able to disallow (Vector x Vector x Vector) input, for example. You 
normally achieve this in Julia by writing two separate methods, which is 
what you already did. Do you have a very good reason to merge those to 
methods?

With respect to your memory constraints, you should not use transpose 
anyway, because that creates a copy. The following uses minimal memory, 
scales Z in-place, and works for both your input cases (it is allowed to 
index into a scalar), but doesn't solve your type signature problem:

function scaleRestore!(Z, shift, stretch)
    for j in 1:size(Z, 2), i in 1:size(Z, 1)
        Z[i, j] = Z[i, j] * stretch[j] + shift[j]
    end
    return Z
end

If you don't want in-place, just create an output array first.


On Friday, October 14, 2016 at 10:35:56 AM UTC+2, Martin Florek wrote:
>
> Thanks DNF,
> but I want to just merge version 1 and 2 with limited to one vector - two 
> scalars OR one matrix - two vectors into a single definition. On the 
> function f_scaleRestore does not matter, can have different forms. I also 
> have requirements for memory, so I use broadcast(). So the question is how 
> to write a function, where I enter only two kinds of desired input? 
>  Probably the solution is Union{}, but how to implement it.
>
> On Friday, 14 October 2016 10:03:15 UTC+2, DNF wrote:
>>
>> Hmm. I slightly misread the way you had set up your code. I thought you 
>> wanted your code to cover three cases: all scalar, one vector - two 
>> scalars, and one matrix - two vectors.
>>
>> So to be clear: defining the function:
>>
>> scaleRestore(a, b, c) = a .* b' .+ c'
>>
>> covers both your cases and then some others. Unless you have some 
>> particular reason to constrain the inputs in some way, I wouldn't add all 
>> the type declarations, but just leave the function generic.
>>
>>
>> On Friday, October 14, 2016 at 9:55:21 AM UTC+2, DNF wrote:
>>>
>>> This should work for the three cases you have set up:
>>>
>>> f_scaleRestore(a, b, c) = a .* b' .+ c'
>>>
>>>
>>> On Friday, October 14, 2016 at 9:12:55 AM UTC+2, Martin Florek wrote:
>>>>
>>>> Hi all,
>>>>
>>>> I have the following two functions and I want to sensibly merge them 
>>>> into one. How to marge headers and body of function for Matrix and Vector?
>>>> - 
>>>> f_scaleRestore(a::Float64, b::Float64, c::Float64) = a * b + c;
>>>> -  
>>>> - # version 1
>>>> - function scaleRestore(Z::Matrix{Float64}, shift::Vector{Float64}, 
>>>> stretch::Vector{Float64})
>>>> -   broadcast(f_scaleRestore, Z, stretch', shift')
>>>> - end
>>>> -  
>>>> - # version 2
>>>> - function scaleRestore(Z::Vector{Float64}, shift::Float64, stretch::
>>>> Float64)
>>>> -   broadcast(f_scaleRestore, Z, stretch, shift)
>>>> - end
>>>>
>>>>
>>>> Thanks in advance,
>>>> Martin
>>>>
>>>

Reply via email to