Message Boards Message Boards

7
|
7942 Views
|
2 Replies
|
11 Total Likes
View groups...
Share
Share this post:

Dynamically changing a binary array with BinaryArraySetter

Posted 11 years ago
At the Wolfram SS summer school, we often find it useful to play around with intial conditions for simple computational systems like Turing machines and cellular automata.

In these cases, it is convenient to be able to interactively set the elements of a binary vector or matrix.

Here is some self-contained code that I recently wrote that achieves just this:

 SetAttributes[BinaryArraySetter, HoldFirst];
 BinaryArraySetter[x_Symbol,opts___] := With[
     {dims = Dimensions[x],
      sz = OptionValue[{opts,PixelConstrained->False},PixelConstrained]}, With[
     {ndim = Length[dims]},
     If[1 <= ndim <= 2,
     EventHandler[
         Dynamic[
             ArrayPlot[
                If[ndim == 1, {x}, x],
                opts, Mesh -> True, Frame->True,
                PixelConstrained -> sz],
            TrackedSymbols :> {x}
        ],
        {"MouseClicked" :> With[
            {v = Ceiling @ Apply[{Last[dims]-#2,#1}&,
                MousePosition["Graphics"]/Replace[sz, False -> 1]]},
            If[ArrayQ[x, 1|2, IntegerQ] && 1 <= First[v] <= First[dims] && 1 <= Last[v] < Last[dims],
                With[{v2 = Sequence @@ If[ndim == 1, Last, Identity] @ Ceiling[v]},
                    x[[v2]]=1-x[[v2]]
                ]
            ]
        ]}
    ],
    Return[$Failed]
]]];

Use it in the following way:
x = RandomInteger[1, {15, 15}];
BinaryArraySetter[x, PixelConstrained -> 10]

By clicking on individual cells, you can toggle the corresponding element of the array between 0 and 1. The array can be 1 or 2 dimensional.

Here's a picture:



Hope someone else finds this useful!
POSTED BY: Taliesin Beynon
2 Replies
Thanks, this is useful
POSTED BY: Peter Barendse
Very neat, Tali. I also did something similar in this answer. The value of the matrix is stored in the variable tds.

 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},
 AppearanceElements->None,FrameMargins->0]

POSTED BY: Vitaliy Kaurov
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