MethodError: no method matching S(::Float64, ::Int64)

#1

Hello,

I am newbie in julia, writing my first code! So, I apologize in advance if my question is a bit stupid.

What I’m doing:

include("S.jl")
using FFTW
L = 5       # Interval length
N = 10      # Number of spatial partitions
h = (2*L)/N # Space step 
x = -L:h:L  # Space discretized, length: N+1 

u      = Array{Float64,2}(undef,n,N+1) # Pre-allocate matrix u
u[1,:].= 0                             # Initial condition U(x,0) = 0
...
inputS = real(fft(u[1,:])) # Apply Fast Fourier Transform
...
S.(inputS,N)

And S is a very simple script:

function S(x::Array{Float64,1},N::Int64)
	s = Array{Float64,1}(undef,N+1)
	for i = 1:N+1
		if x[i] > 0
			s[i] = 1
		else
			s[i] = 0
		end
	end
	return s
end

When I try to run the instruction S.(inputS,N) I get the following error massage:
MethodError: no method matching S(::Float64, ::Int64)

To debug, I ran the following code in the REPL:

	s = Array{Float64,1}(undef,N+1)
	for i = 1:N+1
		if inputS[i] > 0
			s[i] = 1
		else
			s[i] = 0
		end
	end

It ran without any problems and did the expected.

The last test I did was to initialize the variable N in the S.jl script, then I got a different error:
ERROR: ArgumentError: invalid index: false of type Bool

Just to be clear about the types and sizes of variables that are being used:

typeof(N)      # = Int64
typeof(inputS) # = Array{Float64,1}
size(inputS)   # = (11,)
typeof(s)      # = Array{Float64,1}
size(s)        # = (11,)

Someone can help me please?

Thank you,
Tiago

0 Likes

#2

Why are you using broadcasting S.(inputS,N) (note the dot) instead of a normal function call S(inputS, N)?

0 Likes

#3

Oh ok, without the dot it works all fine.
I think i get it, so it’s because the way that i defined function S.

function S(x::Array{Float64,1},N::Int64)
...
end

Since I’m already saying that x is an array it is not necessary to broadcasting S, it’s that right?
Instead, if I defined S like:

function S(x::Float64,N::Int64)
...
end

I could call with the dot? S.(inputS,N). Well I tried right now and gives me the BoundsError.

0 Likes

#4

But you are presumably still doing x[i] > 0 etc in that function, but x is a Float.

0 Likes

#5

Yes, you’re right. Thank you so much! I understood a bit more about broadcasting and fuctions inputs :slight_smile:

0 Likes

#6

Pretty much, yes. Broadcasting is a way to apply a scalar function across one or more arrays (or other collections). The function you broadcast can have any input types; the decision about whether to call f(x) or f.(x) is simply whether you want f to be called on the whole x or on each element of x.

0 Likes

#7

Also note that:

 Array{Float64,1} == Vector{Float64}
 Array{Float64,2} == Matrix{Float64}

It makes that kind of code more readable.

1 Like