# Solving optimization problem with matrix variable

Hello all,

I have been working on an optimization problem with a matrix variable in R, but I haven't managed to get a numerical solution, as I am receiving an error message. Below is a simple example representing my code:

``````Xrs1 = matrix(runif(n=10*3, min=0, max=1), nrow=10, ncol=3)
Xrs2 = matrix(runif(n=40*3, min=0, max=1), nrow=40, ncol=3)
Xdr2 = matrix(runif(n=40*2, min=-5, max=5), nrow=40, ncol=2)

d = fields::rdist(Xrs1, Xrs2)

dr=\(Xdr1) fields::rdist(Xdr1, Xdr2)

f=\(Xdr1) sum( (dr(Xdr1) - d)^2 )

optim(par=matrix(0, nrow=10, ncol=2), fn=f, method="BFGS")
``````

I receive an error, despite the fact that the function f works perfectly with the initial solution or any other numerical matrix with that dimensions.

I would appreciate any help.

I get a non-conformable array error

``````Error in dr(Xdr1) - d : non-conformable arrays
``````

which is odd because there's no `Xdr1` in namespace. Could you post your code in the form of a `reprex` (see the FAQ), please?

optim has restrictions for what `par` can contain. It wants a vector, and can't handle your matrix, it was implicitly converting your matrix into a vector, and then this failed the subtraction.
With the method below f() expects a vector and makes a matrix from it.

``````Xrs1 = matrix(runif(n=10*3, min=0, max=1), nrow=10, ncol=3)
Xrs2 = matrix(runif(n=40*3, min=0, max=1), nrow=40, ncol=3)
Xdr2 = matrix(runif(n=40*2, min=-5, max=5), nrow=40, ncol=2)

d = fields::rdist(Xrs1, Xrs2)

dr=\(Xdr1) fields::rdist(Xdr1, Xdr2)

f=\(x) {
xm <- matrix(x,nrow=10,ncol=2)
sum( (dr(xm) - d)^2 )}

(matrix_as_vec <- c(matrix(0, nrow=10, ncol=2)))
(opt_result <- optim(par=matrix_as_vec, fn=f, method="BFGS"))

matrix(opt_result\$par,nrow=10,ncol=2)``````
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.