Skip to main content
2 of 8
added 917 characters in body
Luis Mendo
  • 106.7k
  • 10
  • 139
  • 382

MATL, 19 bytes

,!ix"0GYs@12XQ!g]v! 

Input order is M, H, V. The latter two are column vectors. ; is the row separator.

Try it online! Or verify all test cases: 1, 2, 3, 4, 5.

Luis Mendo
  • 106.7k
  • 10
  • 139
  • 382