How to draw an arrow in Matlab?

user3668129 picture user3668129 · Sep 8, 2014 · Viewed 77.1k times · Source

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

Code example:

function [ output_args ] = example( input_args )

figure ('Name', 'example');
x = [10 30]
y = [10 30]
xlim([1, 100])
ylim([1, 100])
arrow (x, y) ???
end

Is there any function in matlab that can draw arrow ? Thanks

Answer

thewaywewalk picture thewaywewalk · Sep 8, 2014

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')

enter image description here

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