Message Boards Message Boards

[Solved] How to specify this NMaximize problem without generating errors?

Posted 1 year ago

I wish to maximize a discrete function whose variable are array indices. Here's a toy version of it:

pselect[A_, lenA_, cindices_] := 
  Product[A[[r, cindices[[r]]]], {r, 1, lenA}];

Here's an example instance of the problem:

myArray = {{37, 20, 27, 35, 39}, {36, 32, 35, 39}, {28, 36, 30, 
    28}, {33, 38, 25}};
myindices = {2, 4, 3, 1};
pselect[myArray, 4, myindices]
(* 772200 *)

I specified (apparently incorrectly) the maximization like this:

NMaximize[{pselect[myArray, 4, ci], 
  ci \[VectorLessEqual] {5, 4, 4, 3}}, 
 ci \[Element] Vectors[4, PositiveIntegers]]

which complains bitterly

Part::partd: Part specification ci[[1]] is longer than depth of object.
Part::pkspec1: The expression ci[[1]] cannot be used as a part specification.
Part::partd: Part specification ci[[2]] is longer than depth of object.
Part::pkspec1: The expression ci[[2]] cannot be used as a part specification.
Part::partd: Part specification ci[[3]] is longer than depth of object.
General::stop: Further output of Part::partd will be suppressed during this calculation.
Part::pkspec1: The expression ci[[3]] cannot be used as a part specification.
General::stop: Further output of Part::pkspec1 will be suppressed during this calculation.

but followed by the correct solution:

{2.08073*10^6, {ci -> {5, 4, 2, 2}}}

How to specify the problem without generating errors?

Thank you!

POSTED BY: Richard Frost
5 Replies

To avoid premature evaluation of pselect you can give a numerical pattern for cindices:

pselect[A_, lenA_, cindices : {__Integer}]:= Product[A[[r, cindices[[r]]]], {r, 1, lenA}];
POSTED BY: Gianluca Gorni

Oh I see, the arguments to pselect are evaluated prior to NMaximize. Thanks for the tip about Pattern (:). After a bit of reading it looks very useful.

POSTED BY: Richard Frost

Gina, Your solution - along with the one provided in NMaximize "Possible Issues" both fail.

pselect[A_, lenA_, cindices : {__Integer}] := 
  Product[A[[r, cindices[[r]]]], {r, 1, lenA}];

myArray = {{37, 20, 27, 35, 39}, {36, 32, 35, 39}, {28, 36, 30, 
    28}, {33, 38, 25}};
myindices = {2, 4, 3, 1};
Print[pselect[myArray, 4, myindices]];
NMaximize[{pselect[myArray, 4, ci], 
  ci \[VectorLessEqual] {5, 4, 4, 3}}, 
 ci \[Element] Vectors[4, PositiveIntegers]]

enter image description here

POSTED BY: Richard Frost

Did you Clear[pselect] before redefining? If not, the old definition still lurks.

POSTED BY: Daniel Lichtblau

Ah ha! I had not considered that. Thank you once again :)

POSTED BY: Richard Frost
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract