R/087_zzz_R_specific_convenience.R

Defines functions cvxr_outer scalar_product vdot

Documented in cvxr_outer scalar_product vdot

#####
## DO NOT EDIT THIS FILE!! EDIT THE SOURCE INSTEAD: rsrc_tree/zzz_R_specific/convenience.R
#####

## R-SPECIFIC: Convenience functions with no direct CVXPY counterpart
## vdot, scalar_product, cvxr_outer are R-specific utility functions.

#' Vector dot product (inner product)
#'
#' @description
#' Computes the inner product: sum of element-wise products after flattening.
#' Returns a scalar expression.
#'
#' @param x An Expression or numeric value.
#' @param y An Expression or numeric value.
#' @returns A scalar Expression representing sum(x * y).
#' @export
vdot <- function(x, y) {
  x <- as_expr(x)
  y <- as_expr(y)
  ## Flatten both, elementwise multiply, sum
  sum_entries(vec(x) * vec(y))
}

#' Scalar product (alias for vdot)
#'
#' @inheritParams vdot
#' @returns A scalar Expression representing sum(x * y).
#' @export
scalar_product <- function(x, y) {
  vdot(x, y)
}

#' Outer product of two vectors
#'
#' @description
#' Computes the outer product `x %*% t(y)`. Both inputs must be vectors.
#'
#' @param x An Expression or numeric value (vector).
#' @param y An Expression or numeric value (vector).
#' @returns An Expression of shape (length(x), length(y)).
#' @export
cvxr_outer <- function(x, y) {
  x <- as_expr(x)
  y <- as_expr(y)
  ## Validate: both must be vectors (one dimension == 1)
  if (min(x@shape) != 1L) {
    cli_abort("{.fn cvxr_outer}: {.arg x} must be a vector, got shape {x@shape[1]}x{x@shape[2]}.")
  }
  if (min(y@shape) != 1L) {
    cli_abort("{.fn cvxr_outer}: {.arg y} must be a vector, got shape {y@shape[1]}x{y@shape[2]}.")
  }
  ## Reshape to column and row vectors, then matrix multiply
  n <- expr_size(x)
  m <- expr_size(y)
  x_col <- reshape_expr(x, c(n, 1L))
  y_row <- reshape_expr(y, c(1L, m))
  x_col %*% y_row
}

Try the CVXR package in your browser

Any scripts or data that you put into this service are public.

CVXR documentation built on March 6, 2026, 9:10 a.m.