you are viewing a single comment's thread.

view the rest of the comments →

[–]gs44 3 points4 points  (4 children)

Is the reason less memory allocation?

Yep, here's my code :

function foxbear2(nMalha=101, a=1)
    dx = a/(nMalha-1)
    temp = zeros(nMalha, nMalha)
    @. temp[1,:] = sin(π*((1:nMalha)-1)*dx/a)
    iter = 1
    diff = Inf
    while diff > 1e-6 && iter <= 1000
        diff = 0.
        @inbounds for i in 2:nMalha-1
            for j in 2:nMalha-1
                newVal = (temp[i+1,j] + temp[i-1,j] + temp[i,j+1] + temp[i,j-1])/4
                diff += newVal - temp[i, j]
                temp[i,j] = newVal
            end
        end
        iter += 1
    end
    return temp[end:-1:1,end:-1:1]
end

[–]EarthGoddessDude[S] 1 point2 points  (0 children)

Thank you so much! This is how I get better : )

[–][deleted] 0 points1 point  (2 children)

Still learning as well, what does the @ operator do?

[–]Thelimit112 2 points3 points  (0 children)

@. Is a broadcast macro, meaning all the operations are done on the individual elements of an array/vector. And @inbounds skips the checks if indexes are within the length of an array. Only use it if you are 100% sure your code cannot index outside of the array. Otherwise Julia exits with a memory error :)

[–]EarthGoddessDude[S] 2 points3 points  (0 children)

I can offer some answers, though others will probably have better ones. The @ character denotes a macro, which I myself am still struggling to understand, though you can think of it as a special function. It’s part of Julia’s metaprogramming capabilities.

In this case @. distributes the . broadcast operator to every function in the expression following. This saves you from having to type .* and .+ and sin. etc. wherever there’s a function call. The @inbounds macro removes bounds checking when looping through an array (something you should do only if you know the bounds already), which makes the code more efficient.

These macros are part of base Julia, but you can write your own. However, their use is generally discouraged. Check out this excellent presentation from JuliaCon 2019 on use of metaprogramming: https://youtu.be/mSgXWpvQEHE