改变数组值的交互式绘图(MATLAB)


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;

我试图将零数组的几个元素的值赋给1。基本上,我想创建一个交互式绘图,用户决定他想要打开哪些单元格,然后将他的绘图保存为矩阵。在Python中,使用on_clickMatplotlib非常简单,但Matlab很奇怪,我找不到一个明确的答案。令人恼火的是,在保存更改并检查最终矩阵之前,您无法看到单击的位置。如果你犯了一个错误,你也不能擦掉一个点。

此外,我得到以下错误:Error using sub2ind Out of range subscript. Error in createPattern (line 12) indx = sub2ind([N,N],X,Y);

有什么好办法吗?

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

我发现了这个链接,并修改了代码,以便能够扩展板,也可以选择已经打开的单元格来关闭它们。

现在我需要一种方法来提取board值来保存数组。

最新更新