Boundaries of the matrix in Julia

Viewed 70

I am plotting data in Julia. To extract the y-values I was using a nested for loop

    y = []
    for i in range(0.01,1,step=0.05)
        for j in range(0.01,2,step=0.002)
            a = f(i,j)
            push!(y,a)
        end
    end

And now when ever I run:

plot(x,y)

I get discrete not very nice plots with lines constantly jumping from the beginning to the end.

enter image description here

I am also using moving average function:

moving_average(vs,n) = [sum(@view vs[i:(i+n-1)])/n for i in 1:(length(vs)-(n-1))]
plot(x,moving_average(y,4)

So I was curious is there a way to transform the y-matrix in a way to get rid of these lines in the plot and still be able to apply the moving_average function in the same way?

2 Answers

Your y is not a matrix, it's a vector, so all values are lined up, one after the other. If you want a matrix, you must initialize a 2d array.

Also, you are leaving out the definition of x. That has some influence on what the plot will look like.

I would not write a loop at all here. Just use broadcasting (and I don't see any reason to use range, when start:step:stop is so convenient):

y = f.(0.01:0.05:1, (0.01:0.002:2)')
plot(x, y)

Another alternative is a comprehension:

y = [f(i, j) for i in 0.01:0.05:1, j in 0.01:0.002:2]

If you absolutely must write a loop, you can initialize y as shown here:

r1 = 0.01:0.05:1
r2 = 0.01:0.002:2
y = zeros(Float64, length(r1), length(r2))
for (j, val2) in pairs(r2), (i, val1) in pairs(r1)
    y[i, j] = f(val1, val2)
end

The drawback (aside from the verbosity) is that you must know the output type of f(val1, val2). Maybe it isn't Float64.

BTW, never initialize a vector as [], that creates a Vector{Any} which can cause unexpected results and ruins performance. If your background is from Matlab, then the equivalent of Matlab's [] is Float64[], but you can use any type, like Int[] or ComplexF32[] etc.

if you don't want the dots to be connected, you can try a different plot type

scatter(x,y)
Related