Search code examples
matlabmatlab-figure

Matlab define callback function for mouse click on a biograph


all! This is my first question on stackoverflow! In matlab, I create a biograph and visualize it.

cm = [0 1 1 0 0;1 0 0 1 1;1 0 0 0 0;0 0 0 0 1;1 0 1 0 0];
bg1 = biograph(cm);
view(bg1)

Now I want to define callback function when I click on a certain edge or node. I found from here that I can define callback function for all notes or all edges using

set(bg1, 'NodeCallback', 'NodeCallback_dblclick');

But I am wondering how to define callback function for clicking on a specific node or edge.

Anyone can help? Thank you!


Solution

  • I'm considering nodes in this answer. For edges it would be similar.

    You need to handle the node distinction within the callback function. This function is common to all nodes, but can know which node has been clicked because the node is passed as an input. Within this function you can for example check the ID property of the node, and react differently depending on that.

    So, first define the callback function:

    function node_callbacks(node)
    switch node.ID
    case 'Node 1'
        disp('Hello, I''m node 1');
    case 'Node 2'
        disp('What''s up? This is node 2');
    case 'Node 3'
        disp('Hi! You''ve clicked node 3');
    case 'Node 4'
        disp('I''m node 4 and I don''t want to talk!');
    case 'Node 5'
        disp('Who dares bother node 5??');
    end
    

    and then set that as the callback function for the nodes. You should to that before viewing the graph:

    cm = [0 1 1 0 0;1 0 0 1 1;1 0 0 0 0;0 0 0 0 1;1 0 1 0 0];
    bg1 = biograph(cm);
    set(bg1, 'NodeCallbacks', @node_callbacks)
    view(bg1)