'I would like to record time in seconds each time i am crossing a particular region in Matlab Guide

I would like to track the cursor position within the axes and adds a marker like this for instance(.). Furthermore, I would like to record and display how much time was spent within a particular region (rectangle, indicating green each time the cursor is within the rectangle.)? All this done in Guide . The output in the fig is very different to what I was expecting. See pictures. 1)The first picture is what I was expecting 2)The second pictures is what I have. enter image description here

   % --- Executes on mouse motion over figure - except title and menu.
function finger_WindowButtonMotionFcn(hObject,~, handles)
% hObject    handle to finger (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
pos = get(hObject, 'currentpoint'); % get mouse location on figure
global x;
global y;
x = pos(1); 
y = pos(2); % assign locations to x and y
set(handles.xloc, 'string', ['x loc:' num2str(x)]); % update text for x loc
set(handles.yloc, 'string', ['y loc:' num2str(y)]); % update text for y loc 

% Determine if mouse is within the region

p_x = get(handles.region1,'XData');
p_x = p_x([1 2]);
p_y = get(handles.region1,'YData');
p_y = p_y([1 3]);

ax_xl = get(handles.axes1,'XLim');
ax_yl = get(handles.axes1,'YLim');

ax_units = get(handles.axes1,'Units');
if ~strcmp(ax_units,'pixels')
    set(handles.axes1,'Units','pixels')
end
ax_pos = get(handles.axes1,'Position'); % axes1 position in pixels
if ~strcmp(ax_units,'pixels')
    set(handles.axes1,'Units',ax_units);
end

% convert the patch XData and YData from axes coordinates to figure coordinates in pixels
p_x = (p_x-ax_xl(1))/(ax_xl(2)-ax_xl(1))*ax_pos(3)+ax_pos(1);
p_y = (p_y-ax_yl(1))/(ax_yl(2)-ax_yl(1))*ax_pos(4)+ax_pos(2);

 persistent timein;
 if isempty(timein)
   timein = datetime('now');
end

if x >= p_x(1) && x <= p_x(2) && y >= p_y(1) && y <= p_y(2)
            timein = datetime('now');
    set(handles.region1,'FaceColor','g');
    %writeline(handles.arduinoObj, "4&MOTOR_1_2_3_4&0!");
else
            timeInPatch = seconds(datetime('now')-timein);
            ax = ancestor(handles.region1, 'axes');
            cp = ax.CurrentPoint;
            text(ax, 0.52, cp(1,2), sprintf('%.3f sec.', timeInPatch), ...
                'HorizontalAlignment','Left', ...
                'VerticalAlignment','bottom', ...
                'FontSize', 12, ...
                'FontWeight', 'bold', ...
                'Color', 'b')
    set(handles.region1,'FaceColor','r');
    %writeline(handles.arduinoObj, "0&MOTOR_1_2_3_4&0!");
end


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source