Elementwise multiplication of a matrix with a vector
fpa2 opened this issue · comments
Hello,
i am not sure if I have to ask this question here or on stack overflow, in case the topic does not belong here, please let me know.
I want to use CVXR to find the optimal values of a vector. In the objective function i need to multiply a matrix with this vector in an elementwise way:
b: Nx1 vector
X: Nxp matrix
result: Nxp matrix
Example:
/ # Set the dims
N <- 50
p <- 5
X <- matrix(rnorm(N*p), N, p)
/# to find the optimal values using optim() one could simply have a numeric object
/# say the optimal values are 0.1, -0.2, 0.3, -0.5, 0.6
b <- c(0.1, -0.2, 0.3, -0.5, 0.6)
/# Then we can have the Nxp matrix with the product
/# (where column i of X is multiplied by element i of b) is given by
X*b
b is the vector of coefficient to be optimised.
Using CVXR one must declare
b <- Variable(p)
as Variable object with uses the matrix form, therefore later we can't really multiply as in the previous case.
Also, we don't want to create a matrix of b: Nxp because we need to have one optimal value for all N observations of the i-th column (therefore the mul_elemwise(X, X*b) option wouldn't work as it would give different optimal values for different observations of N - if I am not mistaken).
thanks,
- SO is probably good.
- Beware that the multiplication that R does is far from what you think it is doing. Try:
b <- c(2, 3)
x <- matrix(1, nrow = 3, ncol = 2)
isTRUE(all.equal(x * b, cbind(x[, 1] * b[1], x[, 2] * b[2])))
- You can achieve what you want by using
mul_elemwise
withb[i]
and each column ofX
and combining that withhstack
(equivalent ofcbind
) orvstack
(equivalent ofrbind
) as the case may be.