MATLAB Answers

How can I find indices of an OptimizationExpression array with the value of "Expression with all zero coefficients"?

2 views (last 30 days)
Let an optimization expression is given by: expr = optimexpr(5,1); Suppose that only expr(1) and expr(2) are assigned, and we know that expr(3), expr(4), and expr(5) are empty (Expression with all zero coefficients). How can I find indices of an Optimization Expression array with the values of "Expression with all zero coefficients". For instance, a function returns: inds = [0 0 1 1 1].
Note: This is particularly useful when constructing constraints without for loops. We begin with a relatively large OptimizationExpression, perform necessary operations in a vectorized form, and then only non-zero coefficients are used to form constraints/objective function.

  0 Comments

Sign in to comment.

Accepted Answer

ilker golcuk
ilker golcuk on 20 Dec 2018
The function "evaluate" solves the problem. Evaluating the expression at point 1 (or any other point depending on the problem) implicitly gives the empty cells in the expression.
clear; clc;
% Decision variables
x = optimvar('x',[5,1]);
% Empty expression
expr = optimexpr(size(x));
% Assignments for the expression
expr(1) = x(1);
expr(2) = x(2);
% Detect empty cells in the expression and remove them
inds = expr.evaluate(struct('x',ones(size(x)))) == 0; % Evaluate at point 1.
expr(inds) = [];
% Generate constraints from the expression
% if the empty expressions are not removed, the constraint 0 >= 5 is being generated!!!
cons1 = expr >= 5;

  0 Comments

Sign in to comment.

More Answers (0)

Sign in to answer this question.