Consider the following two functions,
function f(x)
x = x .+ 1
end
function g(x)
x .+= 1
end
My understanding is that they should behave identically, since a .+= b is just syntactic sugar for a = a .+ b. However f does not mutate a global variable passed to it as an argument, while g does.
Can anyone explain to me what is going on here?
Thanks.
This is almost right: x .+= 1 is syntactic sugar for x .= x .+ 1 which does in-place elementwise assignment whereas x = x .+ 1 rebinds x to the new array produced by doing elementwise addition.
Related
I want to loop over a list of variables nad output the variable name and value. E.g., say I have x=1 and y=2, then I want an output
x is 1
y is 2
I suspect I need to use Symbols for this. Here is my approach, but it isn't working:
function t(x,y)
for i in [x,y]
println("$(Symbol(i)) is $(eval(i))") # outputs "1 is 1" and "2 is 2"
end
end
t(1, 2)
Is there a way to achieve this? I guess a Dictionary would work, but would be interested to see if Symbols can also be used here.
One option is to use a NamedTuple:
julia> x = 1; y = 2
2
julia> vals = (; x, y)
(x = 1, y = 2)
julia> for (n, v) ∈ pairs(vals)
println("$n is $v")
end
x is 1
y is 2
Note the semicolon in (; x, y), which turns the x and y into kwargs so that the whole expression becomes shorthand for (x = x, y = y).
I will also add that your question looks like like you are trying to dynamically work with variable names in global scope, which is generally discouraged and an indication that you probably should be considering a datastructure that holds values alongside labels, such as the dictionary proposed in the other answer or a NamedTuple. You can google around if you want to read more on this, here's a related SO question:
Is it a good idea to dynamically create variables?
You can do this by passing the variable names:
x = 1
y = 2
function t(a, b)
for i in [a, b]
println("$(i) is $(eval(i))")
end
end
t(:x, :y)
x is 1
y is 2
At the start of the function, there's no record of the "x"-ness of x, or the "y"-ness of y. The function only sees 1 and 2. It's a bit confusing that you also called your two local variables x and y, I renamed them to show what's happening more clearly.
A solution with dictionaries would be nicer:
dict = Dict()
dict[:x] = 1
dict[:y] = 2
function t(d)
for k in keys(d)
println("$(k) is $(d[k])")
end
end
t(dict)
y is 2
x is 1
If you rather want to see programmatically what variables are present you could use varinfo or names:
julia> x=5; y=7;
julia> varinfo()
name size summary
–––––––––––––––– ––––––––––– –––––––
Base Module
Core Module
InteractiveUtils 316.128 KiB Module
Main Module
ans 8 bytes Int64
x 8 bytes Int64
y 8 bytes Int64
julia> names(Main)
7-element Vector{Symbol}:
:Base
:Core
:InteractiveUtils
:Main
:ans
:x
With any given name it's value can be obtained via getfield:
julia> getfield(Main, :x)
5
If you are rather inside a function than use #locals macro:
julia> function f(a)
b=5
c=8
#show Base.#locals
end;
julia> f(1)
#= REPL[13]:4 =# Base.#locals() = Dict{Symbol, Any}(:a => 1, :b => 5, :c => 8)
Dict{Symbol, Any} with 3 entries:
:a => 1
:b => 5
:c => 8
For a fixed n, I would like to create a function with n variables
f(x_1, ..., x_n)
For example if n=3, I would like to create an algorithm such that
f(x_1, x_2, x_3) = x_1 + x_2 + x_3
It would be very nice to have an algorithm for every n:
f(x_1, ..., x_n) = x_1 + ... + x_n
I don't know how to declare the function and how can create the n variables.
Thank you for your help,
In Julia you can just do
function f(x...)
sum(x)
end
And now:
julia> f(1,2,3)
6
Note that within the function f, x is just seen as a Tuple so you can do whatever you want (including asking for type of elements etc).
More generally you can define function f(x...;y...). Let us give it a spin
function f(x...;y...)
#show x
#show Dict(y)
end
And now run it:
julia> f(1,2,"hello";a=22, b=777)
x = (1, 2, "hello")
Dict(y) = Dict(:a => 22, :b => 777)
Dict{Symbol, Int64} with 2 entries:
:a => 22
:b => 777
Finally, another one (perhaps less elegant) way could be:
g(v::NTuple{3,Int}) = sum(v)
This forces v to be a 3-element Tuple and g be called as g((1,2,3))
If your n is small, you can do this manually thanks to multiple dispatch.
julia> f(x) = x + 1 # Method definition for one variable.
f (generic function with 1 method)
julia> f(x, y) = x + y + 1 # Method definition for two variables.
f (generic function with 2 methods)
julia> f(2)
3
julia> f(2, 4)
7
You could use macro programming to generate a set of these methods automatically, but that quickly becomes complicated. You are likely better off structuring your function so that it operates on either a Vector or a Tuple of arbitrary length. The definition of the function will depend on what you want to do. Some examples which expect x to be a Tuple, Vector, or other similar datatype are below.
julia> g(x) = sum(x) # Add all the elements
g (generic function with 1 method)
julia> h(x) = x[end - 1] # Return the second to last element
h (generic function with 1 method)
julia> g([10, 11, 12])
33
julia> h([10, 11, 12])
11
If you would rather the function accept an arbitrary number of inputs rather than a single Tuple or Vector as you wrote in the original question, then you should define a method for the functions with the slurping operator ... as below. Note that the bodies of the function definitions and the outputs from the functions are exactly the same as before. Thus, the slurping operator ... is just for syntactical convenience. The functions below still operate on the Tuple x. The function arguments are just slurped into the tuple before doing anything else. Also note that you can define both the above and below methods simultaneously so that the user can choose either input method.
julia> g(x...) = sum(x) # Add all the variables
g (generic function with 2 methods)
julia> h(x...) = x[end - 1] # Return the second to last variable
h (generic function with 2 methods)
julia> g(10, 11, 12)
33
julia> h(10, 11, 12)
11
Finally, another trick that is sometimes useful is to call a function recursively. In other words, to have a function call itself (potentially using a different method).
julia> q(x) = 2 * x # Double the input
q (generic function with 1 method)
julia> q(x...) = q(sum(x)) # Add all the inputs and call the function again on the result
q (generic function with 2 methods)
julia> q(3)
6
julia> q(3, 4, 5)
24
I'm trying to make a function that compose a function f(x) by itself N times, something like that:
function CompositionN(f,N)
for i in 1:N
f(x) = f(f(x))
end
return f(x)
I need that the function CompositionN returns another function, not a value.
The solution with ntuple and splatting works very well up to a certain number of compositions, say 10, and then falls off a performance cliff.
An alternative solution, using reduce, is fast for large numbers of compositions, n, but comparatively slow for small numbers:
compose_(f, n) = reduce(∘, ntuple(_ -> f, n))
I think that the following solution is optimal for both large and small n:
function compose(f, n)
function (x) # <- this is syntax for an anonymous function
val = f(x)
for _ in 2:n
val = f(val)
end
return val
end
end
BTW: it is the construction of the composed function which is faster in the approach suggested here. The runtimes of the resulting functions seem to be identical.
You can take advantage of the ∘ function, which allows you to compose multiple functions:
julia> composition(f, n) = ∘(ntuple(_ -> f, n)...)
composition (generic function with 1 method)
julia> composition(sin, 3)(3.14)
0.001592651569876818
julia> sin(sin(sin(3.14)))
0.001592651569876818
Here's a recursive approach:
julia> compose(f, n) = n <= 1 ? f : f ∘ compose(f, n-1)
compose (generic function with 1 method)
julia> compose(x -> 2x, 3)(1)
8
If we're willing to do a little type piracy, we can use the power operator ^ on functions to represent n-th order self-composition:
julia> Base.:^(f::Union{Type,Function}, n::Integer) = n <= 1 ? f : f ∘ f^(n-1)
julia> f(x) = 2x
f (generic function with 1 method)
julia> (f^3)(1)
8
I am trying to use a transpose operator over a vector in order to perform am element-wise addition.
For example, I want to add a column vector a = [a1;a2;a3] to a row vector b = [b1,b2] I should get matrix
M = a+b = [a1+b1, a1+b2; a2+b1, a2+b2; a3+b1, a3+b2].
In MATLAB it is equivalent (if both vectors are row vectors) M = a.'+b
I am trying to get the same in Julia but here is the problem, there is no .' operator in Julia starting from 1.0 version. There is the transpose operator which does not work in broadcasting mode. The adjoint operator is not Valid for me because I work with complex numbers.
a = Vector{ComplexF64}([1+3im,2])
b = Vector{ComplexF64}([0,0,0])
Z = zeros(ComplexF64,3,2)
G = zeros(ComplexF64,3,2)
#. Z = b + a' # Works but takes the complex conjugate
#. Z = b + transpose(a) # DOES NOT WORK!!!! The error is " DimensionMismatch("array could not be broadcast to match destination") "
Z = b .+ transpose(a) # Works but not efficient
#. Z = b + conj(a')
The third case Z = b .+ transpose(a) is not efficient because it makes 2 loops first one for addition b .+ transpose(a), than it runs the second loop one for the assignment of b .+ transpose(a) to Z. While the other 3 cases do it within one loop.
So which is the fastest way?
And why transpose doesn't within Broadcasting?
Thank you in advance
For Hermitian You can just type:
a' .+ b
Example
julia> a = ComplexF64.([1+3im,2])
2-element Array{Complex{Float64},1}:
1.0 + 3.0im
2.0 + 0.0im
julia> b = ComplexF64.([10,20,30])
3-element Array{Complex{Float64},1}:
10.0 + 0.0im
20.0 + 0.0im
30.0 + 0.0im
julia> a' .+ b
3×2 Array{Complex{Float64},2}:
11.0-3.0im 12.0+0.0im
21.0-3.0im 22.0+0.0im
31.0-3.0im 32.0+0.0im
If you want to have just transposition you could define your own unary operator (perhaps from the list of unused unary operators):
¬(a) = permutedims(a)
Now you could do
julia> ¬a
1×2 Matrix{ComplexF64}:
1.0+3.0im 2.0+0.0im
With the aid of broadcasting, the following code will work whether x, y, and z are scalars, vectors of size n, or any combination thereof.
b = zeros(n)
b .= x.*y.*z .+ x
However, I'd like a for-loop. The following for-loop only works when x is a vector of size n, y is a scalar, and z is a scalar.
for i = 1:n
b[i] = x[i]*y*z + x[i]
end
To write the equivalent of b .= x.*y.*z .+ x as a for-loop for any case, I can only think of writing a for-loop for every combination of x, y, and z within if-statements. This can get messy with more variables in more complicated math expressions.
Is there a more elegant way to do what I'd like than using many if-statements?
You could define a wrapper type that indexing into it will give array indexing if wrapped variable is array and repeats the same value for all indices for scalars. I have an example below but it probably is not as efficient as using broadcast. And it is not checking if array lengths are consistent. However, a custom wrapper type would alleviate the situation.
julia> function f(x,y,z)
lx,ly,lz = length(x),length(y),length(z)
maxlen = max(lx,ly,lz)
cx = cycle(x)
cy = cycle(y)
cz = cycle(z)
b = zeros(maxlen)
#inbounds for (xi,yi,zi,i) in zip(cx,cy,cz,1:maxlen)
b[i] = xi*yi*zi+xi
end
return b
end
f (generic function with 1 method)
julia> f(1:3,21,2)
3-element Array{Float64,1}:
43.0
86.0
129.0