cj wyett
cj wyett

Reputation: 152

Inconsistent MethodError: only exists outside call to plots

This is code that works fine:

function band_limited_interpolation()
    
    h=1 
    xmax=10
    x = -xmax:h:xmax
    xx = -xmax-h/20:h/10:xmax+h/20
    
    v = x .== 0
    
    function p(v)
        p = zeros(size(xx))
        for i in 1:length(x)
            p += v[i] * sin.(π*(xx.-x[i])/h) ./ (π*(xx.-x[i])/h)
        end
        p
    end
    
    plot1 = plot(x, v, seriestype=:scatter, legend=false)
    plot!(xx, p(v), xlims=(-10,10), ylims=(-0.5,1.1))

end

band_limited_interpolation()

My lovely output

However, if I try and call p(v) again, I get a method error.

Here is the same function, only the final line has changed:

function band_limited_interpolation()
    
    h=1 
    xmax=10
    x = -xmax:h:xmax
    xx = -xmax-h/20:h/10:xmax+h/20
    
    v = x .== 0
    
    function p(v)
        p = zeros(size(xx))
        for i in 1:length(x)
            p += v[i] * sin.(π*(xx.-x[i])/h) ./ (π*(xx.-x[i])/h)
        end
        p
    end
    
    plot1 = plot(x, v, seriestype=:scatter, legend=false)
    plot!(xx, p(v), xlims=(-10,10), ylims=(-0.5,1.1))
    
    p(v)

end

band_limited_interpolation()

MethodError: objects of type Vector{Float64} are not callable Use square brackets [] for indexing an Array.

Why is this? I can call it just fine in the plot! call?

Upvotes: 1

Views: 35

Answers (1)

cbk
cbk

Reputation: 4370

You are using the name p to refer to two different things:

  1. A function
  2. a Vector{Float64}, specifically p = zeros(size(xx))

The former can be called with p(v), the latter cannot, and will yield the error reported if you attempt to do so. One way or another, that error indicates that in the scope where you are calling p(v) and receiving that error, p is being understood to mean (2). This could happen if you ever pasted p = zeros(size(xx)) into the REPL, or perhaps for other reasons as well. While you may be able to avoid this by being careful with scope, the simplest solution is just not to re-use the variable name p in this way.

Upvotes: 1

Related Questions