Learn R Programming

CVXR (version 1.9.1)

as_cvxr_expr: Convert a value to a CVXR Expression

Description

Wraps numeric vectors, matrices, and Matrix package objects as CVXR Constant objects. Values that are already CVXR expressions are returned unchanged.

Usage

as_cvxr_expr(x)

Value

A CVXR expression (either the input unchanged or wrapped in Constant).

Arguments

x

A numeric vector, matrix, Matrix::Matrix object, Matrix::sparseVector object, or CVXR expression.

Matrix package interoperability

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.

Examples

Run this code
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

Run the code above in your browser using DataLab