# Optimize the product of a matrix and scalar

This code:

``````function objective(xy)
x, y = xy
return (3y^2*x + x^3-m3)*W*(3y^2*x + x^3-m3)
end

xy0 = [x, y]
println(result)

minimizer = result.minimizer
x, y = minimizer
println("x = ", x)
println("y = ", y)
``````

where W=:

``````2×2 Matrix{Float64}:
2.87989e-6  9.85217e-7
9.85217e-7  4.4135e-7
``````

Returns the error:

``````MethodError: Cannot `convert` an object of type Matrix{Float64} to an object of type Float64
Closest candidates are:
convert(::Type{T}, !Matched::Base.TwicePrecision) where T<:Number at twiceprecision.jl:273
convert(::Type{T}, !Matched::AbstractChar) where T<:Number at char.jl:185
convert(::Type{T}, !Matched::CartesianIndex{1}) where T<:Number at multidimensional.jl:130
...

``````

I seem to be able to multiply a scalar by a matrix by a scalar normally:

``````5*W*5
``````

returns:

``````2×2 Matrix{Float64}:
7.19973e-5  2.46304e-5
2.46304e-5  1.10338e-5
``````

Does anyone know why it does not work within the Optim environment, and how to fix it? Thank you!

The `objective` function returns a matrix when it should return a scalar.

1 Like

If `5*W*5` truly is what you would like to do, you might save some work by instead computing `5^2*W`. But since you are treating the result as an objective function, you likely intend to compute an inner product?

3 Likes

Besides being lazy with `W` in the following, I needed also a value for `m3`, but this for example works (assuming your terms with + are vectors

``````using Optim
m3 = 0.3
function objective(xy)
x, y = xy
return [3y^2*x, x^3-m3]'*W*[3y^2*x, x^3-m3]
end
W = [1.0 1.0; 0.0 1.0]
x = 0.0
y = 0.0
xy0 = [x, y]
println(result)

minimizer = result.minimizer
x, y = minimizer
println("x = ", x)
println("y = ", y)
``````

returns

`````` * Status: success

* Candidate solution
Final objective value:     1.283678e-09

* Found with