2
$\begingroup$

I want to solve some optimization problem involving matrices. A toy example related to the problem looks as follows

Ma = Table[RandomVariate[UniformDistribution[{0, 1}]], {q1, 1, 10}, {q2, 1, 10}];
Minimize[{Norm[Part[Ma, 1;;10-d1, 1;;10-d2]-Part[Ma,d1+1;;10, d2 + 1 ;; 10], 2]^2/(10-d1)/(10-d2),And[1 <= d1, d1 <= 5, d2 >= 1, d2 <= 5],Element[ Alternatives[d2,  d1], Integers]}, {d1, d2}]

Minimize does not recognize 10-d1, 10-d2 as a valid Span specification, though returns the valid solution. Obviously, this problem can be solved without use of Minimize, but for certain reasons it is more convenient to use Minimize or NMinimize

$\endgroup$

1 Answer 1

5
$\begingroup$

This is just an evaluation order problem as the d1,d2 are treated as symbolic. You can force d1,d2 to be integers using a pattern test:

(* you don't need the table here either *)
Ma = RandomVariate[UniformDistribution[{0, 1}], {10, 10}];

getMa1[d1_?IntegerQ, d2_?IntegerQ] := Part[Ma, 1 ;; 10 - d1, 1 ;; 10 - d2]
getMa2[d1_?IntegerQ, d2_?IntegerQ] := Part[Ma, d1 + 1 ;; 10, d2 + 1 ;; 10]
Minimize[{Norm[getMa1[d1, d2] - getMa2[d1, d2], 2]^2/(10 - d1)/(10 - d2),
  And[1 <= d1, d1 <= 5, d2 >= 1, d2 <= 5], 
  Element[Alternatives[d2, d1], Integers]}, {d1, d2}]
$\endgroup$
1
  • 2
    $\begingroup$ To save a few bytes you could restrict the Head rather than using PatternTest, e.g., getMa1[d1_Integer, d2_Integer] $\endgroup$
    – Bob Hanlon
    Commented Jun 3, 2021 at 14:47

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.