Search code examples
juliajulia-jumpjulia-studio

How is it possible to have a function of a variable in julia?


if you don't mind, would you please help me that how can I have a function of x as follow:

this function calculate two values for x

function MOP2(x)
    n=length(x);
    z1=1-exp(sum((x-1/sqrt(n)).^2));
    z2=1-exp(sum((x+1/sqrt(n)).^2));
    z=[z1;z2];
    return z
end

in main code I want to have

costfunc=F(x)

but I don't know it exists in Julia or not. in matlab we can have that as following

costfunc=@(x)  MOP2(x)

is there any function like @ in Julia?

Thanks very much.


Solution

  • Yes, there is a syntax for that.

    These are called anonymous functions (although you can assign them a name).

    Here are a few ways to do this.

    x -> x^2 + 3x + 9
    x -> MOP2(x) # this actually is redundant. Please see the note below
    
    # you can assign anonymous functions a name
    costFunc = x -> MOP2(x)
    
    
    # for multiple arguments
    (x, y) -> MOP2(x) + y^2
    
    # for no argument
    () -> 99.9
    
    # another syntax
    function (x)
        MOP2(x)
    end
    

    Here are a few usage examples.

    julia> map(x -> x^2 + 3x + 1, [1, 4, 7, 4])
    4-element Array{Int64,1}:
      5
     29
     71
     29
    
    
    julia> map(function (x) x^2 + 3x + 1 end, [1, 4, 7, 4]) 
    4-element Array{Int64,1}:
      5
     29
     71
     29
    

    Note that you do not need to create an anonymous function like x -> MOP2(x). If a function takes another function, you can simply pass MOP2 instead of passing x -> MOP2(x). Here is an example with round.

    julia> A = rand(5, 5);
    julia> map(x -> round(x), A)
    5×5 Array{Float64,2}:
     0.0  1.0  1.0  0.0  0.0
     0.0  1.0  0.0  0.0  1.0
     0.0  0.0  1.0  0.0  1.0
     1.0  1.0  1.0  1.0  0.0
     0.0  0.0  1.0  1.0  1.0
    
    julia> map(round, rand(5, 5))
    5×5 Array{Float64,2}:
     0.0  1.0  1.0  0.0  0.0
     0.0  1.0  0.0  0.0  1.0
     0.0  0.0  1.0  0.0  1.0
     1.0  1.0  1.0  1.0  0.0
     0.0  0.0  1.0  1.0  1.0
    

    There is also the do syntax while passing functions as arguments.

    If you want to give a name to your anonymous function, you might as well define another function like

    costFunc(x) = MOP2(x) + sum(x.^2) + 4
    

    and use costFunc later.

    If you want to call a function with another name you may write

    costFunc = MOP2
    

    if it is inside a function. Otherwise. in global scope, it is better to add const before the assignment statement.

    const constFunc = MOP2
    

    This is important for type-stability reasons.