R CVXR matrix multiplication %*% Error in mul_dims_promote(lh_dim, rh_dim) : Incompatible dimensions

579 views Asked by At

Hello I am trying to run the example from here: http://rtutorial.altervista.org/lp_solvers.html

A snippet and test where it goes wrong:

library(CVXR)
#create Variable objects that can be manipulated by the solver.
x<-Variable(3)
#coefficients for objective function
C<-c(2,4,3)

#problem:
C %*% x

Error: Error in mul_dims_promote(lh_dim, rh_dim) : Incompatible dimensions

> x
[1] "Variable((3, 1), nonneg=FALSE, nonpos=FALSE, pos=FALSE, neg=FALSE, complex=FALSE, imag=FALSE, symmetric=FALSE, diag=FALSE, PSD=FALSE, NSD=FALSE, hermitian=FALSE, boolean=FALSE, integer=FALSE, )"
> C
[1] 2 4 3
> 
> dim(x)
[1] 3 1
> dim(C)
NULL
> 
> class(x)
[1] "Variable"
attr(,"package")
[1] "CVXR"
> class(C)
[1] "numeric"

The problem might be in

%*%

which is defined in three different packages: Help on topic '%*%' was found in the following packages:

Matrix Multiplication (in package base in library /usr/lib/R/library) Matrix manipulation with gmp (in package gmp in library /home/gnowak/R/x86_64-pc-linux-gnu-library/3.6) Matrix (Cross) Products (of Transpose) (in package Matrix in library /home/gnowak/R/x86_64-pc-linux-gnu-library/3.6)

Any hints or tips? Thank you.

1

There are 1 answers

3
Mark Neal On BEST ANSWER

Try replacing the line C<-c(2,4,3) with C <- matrix(c(2,4,3), nrow = 1). That follows the syntax of the later example on that web page, and then that example works for me. The later example now works for me too, (hat tip Jordan) - replace ‘x3 <- Int(1)’ with ‘x3 <-Variable(1, integer=TRUE)’, though the link will probably be updated shortly.