View source: R/005_zzz_R_specific_utility.R
| as_cvxr_expr | R Documentation |
Wraps numeric vectors, matrices, and Matrix package objects as CVXR Constant objects. Values that are already CVXR expressions are returned unchanged.
as_cvxr_expr(x)
x |
A numeric vector, matrix, Matrix::Matrix object, Matrix::sparseVector object, or CVXR expression. |
A CVXR expression (either the input unchanged or wrapped in Constant).
Objects from the Matrix package (dgCMatrix, dgeMatrix,
ddiMatrix, sparseVector, etc.) are S4 classes.
Because S4 dispatch preempts S7/S3 dispatch, raw Matrix objects cannot be
used directly with CVXR operators (+, -, *, /, %*%, >=, ==,
etc.).
Use as_cvxr_expr() to wrap a Matrix object as a CVXR Constant before
combining it with CVXR variables or expressions. This preserves sparsity
(unlike as.matrix(), which densifies).
Base R matrix and numeric objects work natively with CVXR operators —
no wrapping is needed.
x <- Variable(3)
## Sparse Matrix needs as_cvxr_expr() for CVXR operator dispatch:
A <- Matrix::sparseMatrix(i = 1:3, j = 1:3, x = 1.0)
expr <- as_cvxr_expr(A) %*% x
## All operators work with wrapped Matrix objects:
y <- Variable(c(3, 3))
expr2 <- as_cvxr_expr(A) + y
constr <- as_cvxr_expr(A) >= y
## Base R matrix works natively (no wrapping needed):
D <- matrix(1:9, 3, 3)
expr3 <- D %*% x
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.