Rowwise function call

Hi, I am new to Julia and my terminology should be tribble. I am working with DifferentialEquations.jl, I am trying to calculate histograms of solutions at each point, basically, I have an array of solutions.
arrsol size (101, 2000)
I want to apply the following function to each point and store an array of (101, 100) It works fine if the input shape is (2000*101, 1) but it is not what I am looking for, here is the function, any help is appreciated


function kernalHist(x, rk)
    dr = rk[2] - rk[1]
    den = exp.(-(rk .- x).^2 ./ (2*dr^2))
    den ./= sum(den) + 1e-16
    (sum(den .*(rk[2]-rk[1]), dims=1) ./ sum(den .*(rk[2]-rk[1])) )./ (rk[2]-rk[1])
end

n = 201
rk = LinRange(-10,10, n)
rk = reshape(rk, (1,n))
kernelHist(randn(1000,1),rk)
plot(kernelHist(randn(1000,1),rk)[1,:])

The question is how to make it output (1000, n) when input is randn(1000, 200000), I am still not fully familiar with looping and the correct way of appending in julia, especially if DifferentialEquation.jl is used. Note the output is used to calculate a loss function.

Welcome!

I’m having a hard time understanding exactly what you’re trying to do. But perhaps you’re looking for something like this?

# apply kernelHist to each row of the input matrix
z = [kernelHist(c,rk) for c in eachrow(randn(1000,1))]
# now stack the output of each row into a matrix
reduce(vcat,z)

I’ll also warn you that randn(1000, 200000) is a pretty big matrix. It will fit in your computer’s memory but be careful about making it much bigger. It might be better to form and compute your result one row at a time. For example:

# equivalent to the above with randn(1000, 200000)
z = [kernelHist(randn(200000),rk) for _ in 1:1000]

Unlike MATLAB, NumPy, etc, it isn’t necessary to try to vectorize everything in Julia – it can be just as fast (or faster!) to do things one at a time.

PS: you missed a . in your definition of kernelHist. It doesn’t change the output but it will cause it to run less efficiently – not a serious problem but it’s good to form good habits. You probably meant to write den = exp.(.-(rk .- x).^2 ./ (2*dr^2)) (note the unary .- near the front). Since this is a common mistake, there’s a helpful macro @. that you can use to automatically dots everywhere in an expression den = @. exp(-(rk - x)^2 / (2*dr^2)) if you find that easier.

1 Like