## Create Efficient Optimization Problems

When a problem has integer constraints, `solve` calls `intlinprog` to obtain the solution. For suggestions on obtaining a faster solution or more integer-feasible points, see Tuning Integer Linear Programming.

Before you start solving the problem, sometimes you can improve the formulation of your problem constraints or objective. Usually, it is faster for the software to create expressions for objective function or constraints in a vectorized fashion rather than in a loop. Suppose that your objective function is

`$\sum _{i=1}^{30}\sum _{j=1}^{30}\sum _{k=1}^{10}{x}_{i,j,k}{b}_{k}{c}_{i,j},$`

where `x` is an optimization variable, and `b` and `c` are constants. Two general ways to formulate this objective function are as follows:

• Use a `for` loop. In this case,

```expr = optimexpr; for i = 1:30 for j = 1:30 for k = 1:10 expr = expr + x(i,j,k)*b(k)*c(i,j); end end end```

Here, `expr` contains the objective function expression. While this method is straightforward, it can take excessive time to loop through many levels of `for` loops.

• Use a vectorized statement. Vectorized statements generally run faster than a `for` loop. You can create a vectorized statement in several ways:

• Expand `b` and `c`. To enable term-wise multiplication, create constants that are the same size as `x`.

```bigb = reshape(b,1,1,10); bigb = repmat(bigb,30,30,1); bigc = repmat(c,1,1,10); expr = sum(sum(sum(x.*bigb.*bigc)));```
• Loop once over `b`.

```expr = optimexpr; for k = 1:10 expr = expr + sum(sum(x(:,:,k).*c))*b(k); end```
• Create an expression differently by looping over `b` and then summing terms after the loop.

```expr = optimexpr(30,30,10); for k = 1:10 expr(:,:,k) = x(:,:,k).*c*b(k); end expr = sum(expr(:));```

Watch now