How can I change the elements of a matrix when hovering over its figure with the mouse?

2 Ansichten (letzte 30 Tage)
I am trying to write a code that does the following: the user inserts the values for the row and column numbers for a matrix with values of 0. Then, when displaying the said matrix (as a white grided figure), whenever the mouse hovers over a matrix cell, the value of that becomes 1 and the cell's background is turned black. When hovering again on that cell, it turns back to 0 and white background, respectively. I'm a rather novice in MatLab so there might be simple stuff that I still didn't get right.
Here is my main .m file:
close all; clear all; clc; format long e;
r = input('How many rows do you want? ');
c = input('How many columns do you want? ');
M = zeros(r, c);
disp('Press a key when you want to start...');
clc;
stop = 'n';
figure
while stop == 'n';
imagesc(M); colormap('gray');
set(gcf,'WindowButtonMotionFcn', @mouseMove);
for i = 1: r,
for j = 1 : c,
if (x == i && y == j)
M{i, j} = 1 - M{i, j};
end
end
end
stop = input('Stop? (y/n) \n');
end
hold off;
And here's my mouseMove function:
function [x, y] = mouseMove
[x, y] = get (gca, 'CurrentPoint');
Please help me understand what I did wrong.

Akzeptierte Antwort

Giorgos Papakonstantinou
Giorgos Papakonstantinou am 13 Dez. 2014
Hi Bogdan! Maybe you can try this:
close all; clear all; clc;
fig = figure;
set(fig, 'Color',[0,0.5,0.5]);
grid on;
r = input('How many rows do you want? ');
c = input('How many columns do you want? ');
M = zeros(r, c);
img = imagesc(M, [0 1]);
title('press space to stop')
colormap(gray)
set(gcf,'WindowButtonMotionFcn', @(obj, evd, x)mouseMove(obj, evd, img), ...
'KeyPressFcn', @(obj, evd)StopButtonMotion(obj, evd));
The WindowButtonMotionFcn:
function mouseMove(obj, evd, img)
persistent previousIndex
Coord = get (gca, 'CurrentPoint');
x = Coord(1, 2); % rows
y = Coord(1, 1); % cols
m = get(img, 'CData');
s = size(m);
% Is the mouse of over th image ?
idx1 = bsxfun(@(a, b) a>=b, [x, y], [0.5 0.5]);
idx2 = bsxfun(@(a, b) a<=b, [x, y], [s(1) s(2)] + 0.5);
flag = all([idx1 idx2], 2);
if any(flag)
ii = round(x);
jj = round(y);
index = [ii, jj];
if ~isequal(index, previousIndex)
m(ii, jj) = 1 - m(ii, jj);
set(img, 'CData', m)
previousIndex = index;
end
end
The KeyPressFcn:
function StopButtonMotion(obj, evd)
if strcmp(evd.Key, 'space');...
set(gcf, 'WindowButtonMotionFcn', '');
end;

Weitere Antworten (0)

Kategorien

Mehr zu Environment and Settings finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by