1

Let the variables A and B be n x 1 doubles and c be a scalar. My goal is to sum the values in A corresponding to indices for which the optimization variable x is greater than B. I have written this up below:

x = optimvar('x',n); % Creates optimization variable 
objfun = sum(x); % Creates objective function
constraint = sum(A(x>=B))>=c; % Constraint based on logical indexing

The third line in the code above returns an error message because optimization variables are not compatible with inequality indexing. Specifically, x>=B cannot be input as indexes into A. Is there a way around this? Or am I thinking about this the wrong way?

Thank you!

1
  • In optimization models, we typically use binary decision variables to model this. Commented Oct 9, 2020 at 2:23

1 Answer 1

1

You need to use function handles for both, the objective function as well as the constraint-function:

objfun = @(var) sum(var); 
constraint = @(var) sum(A(var>=B)) >= c;

In fact, for the objective function objfun, you may also use objfun = @sum. This is a function handle. You can think of it as a pointer or reference to a certain function. Function, which work with one input can be used directly (with @). The optimizer calls the function and uses the optimization variable as input.

Now, if you have multiple inputs, you need to create a function, where you define all inputs but one. For this, you create an anonymous function handle, where you tell the handle what variables are placed where: @(var) sum(A(var>=B)) >= c. The variable var is the changing input and the other variables A, B, and c are taken from the workspace at the point of definition (i.e. the function handle is unaffected if you change the variables later or even delete them).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.