Home > Net >  Interactive plot to change array values (MATLAB)
Interactive plot to change array values (MATLAB)

Time:11-29

N = 500;
pattern = zeros(N,N);

grid on
plot(pattern)
% gets coordinates of modified cells
[x,y] = ginput;
% convert coordinates to integers
X = uint8(x);
Y = uint8(y);
% convert (X,Y) into linear indices
indx = sub2ind([N,N],x,y);
% switch desired cells on (value of 1)
pattern(indx) = 1;

I'm trying to assign several elements of a zeros array the value of 1. Basically I want to create an interactive plot where the user decides what cells he wants to turn on and then save his drawing as a matrix. In Python it's very simple to use the on_click with Matplotlib, but Matlab is weird and I can't find a clear answer. What's annoying is you can't see where you clicked until you save your changes and check the final matrix. You also can't erase a point if you made a mistake.

Moreover I get the following error : Error using sub2ind Out of range subscript. Error in createPattern (line 12) indx = sub2ind([N,N],X,Y);

Any idea how to fix it?

CodePudding user response:

function CreatePattern
    hFigure = figure;
    hAxes = axes;
    axis equal;
    axis off;
    hold on;
    N = 3; % for line width
    M = 20; % board size
    squareEdgeSize = 5;

    % create the board of patch objects
    hPatchObjects = zeros(M,M);
    for j = M:-1:1
        for k = 1:M
            hPatchObjects(M - j  1, k) = rectangle('Position', [k*squareEdgeSize,j*squareEdgeSize,squareEdgeSize,squareEdgeSize], 'FaceColor', [0 0 0],...
                'EdgeColor', 'w', 'LineWidth', N, 'HitTest', 'on', 'ButtonDownFcn', {@OnPatchPressedCallback, M - j  1, k});
        end
    end

    
    Board = zeros(M,M);
    playerColours = [1 1 1; 0 0 0];
    
    xlim([squareEdgeSize M*squareEdgeSize]);
    ylim([squareEdgeSize M*squareEdgeSize]);
    
    function OnPatchPressedCallback(hObject, eventdata, rowIndex, colIndex)
        % change FaceColor to player colour
        value = Board(rowIndex,colIndex);
        if value == 1
            set(hObject, 'FaceColor', playerColours(2, :));
            Board(rowIndex,colIndex) = 0; % update board
        else 
            set(hObject, 'FaceColor', playerColours(1, :));
            Board(rowIndex,colIndex) = 1; % update board
        end

    end
end

I found this link and modified the code to be able to expand the board and also select cells that have been turned on already to switch them off.

Now I need a way to extract that board value to save the array.

  • Related