MethodError: Cannot `convert` an object of type Vector{Float64} to an object of type Float64

What does this error mean?

That an object somewhere in the code is specified as Vector{Float64} and Julia cannot convert it to Float64? I thought it didn’t matter so long as the type was matched (i.e. both Float64).

julia> a = 3.0;

julia> convert(Float32, a)
3.0f0

julia> convert(Float32, [a, a])
ERROR: MethodError: Cannot `convert` an object of type Vector{Float64} to an object of type Float32
Closest candidates are:

you cannot convert an array into a scalar and it doesn’t make sense anyway

A common cause is setindex!:

julia> x = rand(3);

julia> x[1] = [1.0];
ERROR: MethodError: Cannot `convert` an object of type Vector{Float64} to an object of type Float64
2 Likes

Hi everybody,
I have a similar question to the extent that when I use setindex! Julia raises the same error
My script:

The error message :

Do you have any clue ?

Tanks in advance !

Probably best to start a separate thread about your issue. That said, your error is relatively clear I would have thought - you’re trying to set a value of yhat, but you’re passing a vector, which is what [1 1]*xhat returns, as xhat is a two-element vector:

julia> [1 1]*rand(2)
1-element Vector{Float64}:
 1.074598145683848

If you just want to sum the elements of xhat why not just use sum? I probably would have written something like:

y = [0 1 2.5 4.1 5.8 7.5]
x̂ = [0, 0]
n = 100
ϵ = 0.01
ŷ = zeros(5)

for k in 1:n
	for l in 1:5
		ϵ₁, ϵ₂ = rand(2)
		A = [1 0; ϵ₁ 0.3]
		B = [ϵ₂; 1 - ϵ₂]
		x̂ = A*x̂ + B
		ŷ[l] = sum(x̂)
	end

	if ŷ*y < ϵ
		scatter(x̂[1], x̂[2], aspect_ratio = 1)
	else
		scatter!(x̂[1], x̂[2], aspect_ratio = 1)
	end
	
	ŷ = zeros(5)
end

Are you coming from MATLAB by any chance? Make sure to read the Julia docs, including the section on notable differences from MATLAB, to make your life easier.

@nilshg thank you very much for your quick answer
I got your point, however what would be the general case ? Like in the photo below ?
Capture

what general case? are you look for element wise set index? .= ?

please stop sending screenshots and try to send MWE (minimal working example) snippet in the future

What I mean by general case is to set a value of an element of a matrix with a dot product (here [m1 m2] and xhat)

the dot product will be calculated first. it should give you a scalar, you can set an element of a matrix to a scalar regardless how you got that scalar.

In Julia a dot product is computed by dot(x,y) or x ⋅ y, not x' * y like in Matlab. E.g.

julia> using LinearAlgebra

julia> dot([1 ; 2], [3; 4])
11

julia> [1 ; 2] ⋅ [3; 4]
11

julia> A = zeros(2,2)
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0

julia> A[1,1] = [1 ; 2] ⋅ [3; 4]
11

Do read this documentation. It’ll save you a whole lot of trouble. Noteworthy Differences from other Languages · The Julia Language.

Thank you all for your help!
I’ll check your documentation!