Using the mouse coordinates to index a matrix

5

0

I would like to "write" on to a matrix using the mouse. That is, I would like to use the integer value of Locator coordinates (p) to index a matrix. Then, if the mouse button is down, write a 1 in that location. That approach doesn't seem to work since, when attempting to do something like M[[Sequence @@ Round [p]]], the coordinate p is actually a dynamic quantity, which can't be converted to two integer indices by Sequence @@ Round.

Is there any way to do this? or, Is there an equivalent workaround that gets the same result. The simplest example would be using the mouse to input a freehand black and white drawing as pixels on a matrix, which could later be subject to image processing algorithms.

user2238171

Posted 2013-04-02T23:50:49.473

Reputation: 143

Related: https://mathematica.stackexchange.com/q/51952/7339

– expression – 2021-01-30T07:11:21.763

Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the FAQs! 3) When you see good Q&A, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. ALSO, remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign`

– Vitaliy Kaurov – 2013-04-03T03:26:34.277

Answers

5

Manipulate[x = ConstantArray[0, 9 {1, 1}];
 Row[{EventHandler[Dynamic[tds = Reverse[Transpose[x]];
     MatrixPlot[tds, PlotRangePadding -> 0, Mesh -> All, 
      ImageSize -> {300, 300}, 
      ColorRules -> {1 -> Black, 
        0 -> None}]], {"MouseClicked" :> (pos = 
        Ceiling[MousePosition["Graphics"]];
       x = ReplacePart[x, pos -> 1 - x[[Sequence @@ pos]]];)}], 
   Dynamic@Magnify[MatrixForm[tds], 2]}], {pos, 
  ControlType -> None}, {x, ControlType -> None}, {tds, 
  ControlType -> None}, AppearanceElements -> None, FrameMargins -> 0]

enter image description here

Vitaliy Kaurov

Posted 2013-04-02T23:50:49.473

Reputation: 66 672

Nice! A click and drag to fill would be a nice addition :) – rm -rf – 2013-04-03T01:59:52.030

@rm-rf thanks ;) – Vitaliy Kaurov – 2013-04-03T03:25:36.270

And now you're most of the way to a game of minesweeper! – bill s – 2013-04-03T07:01:41.973