Home > other >  Matlab: How to save multiple variable points from mouse click (with 'ButtonDownFcn') from
Matlab: How to save multiple variable points from mouse click (with 'ButtonDownFcn') from

Time:11-23

I have a figure with some vertical lines added, as such: plot Matlab

figure
x = rand(1,41);
y = 1:41;
H(1)= plot(x,y,'r.');
H(2)= line([x(21) x(21)],[0 max(y)], 'LineWidth', 2, 'Color', 'k');
H(3)= line([x(3) x(3)],[0 max(y)], 'LineWidth', 2, 'Color', 'k');
H(4)= line([x(15) x(15)],[0 max(y)], 'LineWidth', 2, 'Color', 'k');

I would like to be able to click on the lines with the mouse button, and store each of the clicked line index. The following script works but I don't know how to store each index in an array. The 'IndInWorkSpace' keeps changing for each click.

set(H, 'ButtonDownFcn', {@LineSelected, H})

function [indices] = LineSelected(ObjectH, H)
   set(ObjectH, 'LineWidth', 4);
   set(H(H ~= ObjectH), 'LineWidth', 2);
   % Get x and y data of the highlighted lines 
   ind = ObjectH.XData
   assignin('base','IndInWorkSpace',ind);
end

Any help will be much appreciated! Thank you!

CodePudding user response:

An easy fix is to first check if there was already an index found in the base workspace. If there already is a variable IndInWorkSpace, append to it, otherwise assign a new variable.

function LineSelected(ObjectH, H)
    set(ObjectH, 'LineWidth', 4);
    set(H(H ~= ObjectH), 'LineWidth', 2);
    % Get x and y data of the highlighted lines
    ind = ObjectH.XData;
    if evalin('base','exist(''IndInWorkSpace'',''var'')')
        indArray = evalin('base','IndInWorkSpace');
        indArray(end 1) = ind;
    else 
        indArray = ind;
    end 
    assignin('base', 'IndInWorkSpace', indArray);
end
  • Related