MATLAB Examples

Contents

Knapsack demonstration

Ïnteger weights of items

N = 12;
weights = randint(1,N,[1 1000])
weights =

   332   980   158   422   869   765   529   786    40   268   910   269

Values of the items (don't have to be integers)

values = randint(1,N,[1 100])
values =

    30    31    20    79    96    69    88    31    84     2    24    14

Solve the knapsack problem

Call the provided m-file

capacity = 3000;
[best amount] = knapsack(weights, values, capacity);
best
items = find(amount)
best =

   446


items =

     1     4     5     6     7     9

Check that the result matches the contraint and the best value

sum(weights(items))
sum(values(items))
ans =

        2957


ans =

   446