How to draw an arrow in Matlab?

前端 未结 5 1308
旧时难觅i
旧时难觅i 2020-11-30 06:00

I\'m trying to draw an arrow in matlab graph, without any success.

Code example:

function [ output_args ] = example( input_args )

figure (\'Name\',          


        
5条回答
  •  情书的邮戳
    2020-11-30 06:31

    You could abuse quiver, this way you don't have to deal with unhandy normalized figure units by use of annotation

    drawArrow = @(x,y) quiver( x(1),y(1),x(2)-x(1),y(2)-y(1),0 )    
    
    x1 = [10 30];
    y1 = [10 30];
    
    drawArrow(x1,y1); hold on
    
    x2 = [25 15];
    y2 = [15 25];
    
    drawArrow(x2,y2)
    

    enter image description here

    Important is the 5th argument of quiver: 0 which disables an otherwise default scaling, as this function is actually used to plot vector fields. (or use the poperty value pair 'AutoScale','off')

    You can also add additional features:

    drawArrow = @(x,y,varargin) quiver( x(1),y(1),x(2)-x(1),y(2)-y(1),0, varargin{:} )       
    drawArrow(x1,y1); hold on
    drawArrow(x2,y2,'linewidth',3,'color','r')
    

    If you don't like the arrowheads, you need to go back to annotations and this answer is may helpful:

    How do I change the arrow head style in quiver plot?


    Some remarks regarding the comments:

    The arrow head size can be adjust with the 'MaxHeadSize' property, it's not consistent unfortunately. The axes limits need to be set afterwards

    x1 = [10 30];
    y1 = [10 30];
    drawArrow(x1,y1,{'MaxHeadSize',0.8,'Color','b','LineWidth',3}); hold on
    
    x2 = [25 15];
    y2 = [15 25];
    drawArrow(x2,y2,{'MaxHeadSize',10,'Color','r','LineWidth',3}); hold on
    
    xlim([1, 100])
    ylim([1, 100])
    

    enter image description here


    The solution by sed seems to be the best, because it offers adjustable arrow heads.

    I'd just would wrap it into a function:

    function [ h ] = drawArrow( x,y,xlimits,ylimits,props )
    
    xlim(xlimits)
    ylim(ylimits)
    
    h = annotation('arrow');
    set(h,'parent', gca, ...
        'position', [x(1),y(1),x(2)-x(1),y(2)-y(1)], ...
        'HeadLength', 10, 'HeadWidth', 10, 'HeadStyle', 'cback1', ...
        props{:} );
    
    end
    

    which you can call from your script as follows:

    drawArrow(x1,y1,[1, 100],[1, 100],{'Color','b','LineWidth',3}); hold on
    drawArrow(x2,y2,[1, 100],[1, 100],{'Color','r','LineWidth',3}); hold on
    

    giving you quite similar results:

    enter image description here

提交回复
热议问题