代码:
function crossget
ezplot('sin(x)');
set(gcf,'pointer','crosshair');
set(gcf,'WindowButtonMotionFcn',@tempfcn2);
function tempfcn2(hObject, eventdata, handles)
p=get(gca,'currentpoint');
if(isempty(findobj('tag','htext')))
ht=text('tag','htext','string',sprintf(' (%g, %g)', p(1), p(3)),'position',[p(1) +0.5,p(3)]);
else
ht = findobj('tag','htext');
set(ht,'string',sprintf('(%g, %g)', p(1), p(3)),'position',[p(1)+0.5,p(3)]);
end
%也可以响应鼠标点击取点,例如:
function crosshair
ezplot('sin(x)');
set(gcf,'Pointer','crosshair');
set(gcf,'WindowButtonDownFcn',@myfcn);
flag=1;
xlim=get(gca,'xlim');
xlim=[xlim(2)-xlim(1)]*0.025;
ylim=get(gca,'ylim');
ylim=[ylim(2)-ylim(1)]*0.03;
set(gcf,'userdata',[flag,xlim,ylim]);
%----------------
function myfcn(hObject, eventdata, handles);
pt=get(gca,'currentpoint');
pt_show=[pt(1,1),pt(1,2)]
temp=get(gcf,'userdata');
if iscell(temp)
H=temp{2};
temp=temp{1};
end
flag=temp(1);xlim=temp(2);ylim=temp(3);
if flag==1
H.xline=line([pt(1,1)-xlim,pt(1,1)+xlim],[pt(1,2),pt(1,2)]);
H.yline=line([pt(1,1),pt(1,1)],[pt(1,2)-ylim,pt(1,2)+ylim]);
flag=0;
else
set(H.xline,'xdata',[pt(1,1)-xlim,pt(1,1)+xlim]);
set(H.xline,'ydata',[pt(1,2),pt(1,2)]);
set(H.yline,'xdata',[pt(1,1),pt(1,1)]);
set(H.yline,'ydata',[pt(1,2)-ylim,pt(1,2)+ylim]);
end
set(gcf,'userdata',{[flag,xlim,ylim],H});
%以上响应鼠标点击取点,是在matlab窗口中显示坐标值,也是我在论坛中搜索并整理的。实际上,根据不同的需要,只要稍加改动,就可以实现不同功能,如要在图形上记录坐标只需如下改动:
function crosshair
ezplot('sin(x)');
set(gcf,'Pointer','crosshair');
set(gcf,'WindowButtonDownFcn',@myfcn);
flag=1;
xlim=get(gca,'xlim');
xlim=[xlim(2)-xlim(1)]*0.025;
ylim=get(gca,'ylim');
ylim=[ylim(2)-ylim(1)]*0.03;
set(gcf,'userdata',[flag,xlim,ylim]);
function myfcn(hObject, eventdata, handles);
pt=get(gca,'currentpoint');
text('string',sprintf('(%g, %g)', pt(1), pt(3)),'position',[pt(1)+0.5,pt(3)]);
temp=get(gcf,'userdata');
if iscell(temp)
H=temp{2};
temp=temp{1};
end
flag=temp(1);xlim=temp(2);ylim=temp(3);
if flag==1
H.xline=line([pt(1,1)-xlim,pt(1,1)+xlim],[pt(1,2),pt(1,2)]);
H.yline=line([pt(1,1),pt(1,1)],[pt(1,2)-ylim,pt(1,2)+ylim]);
flag=0;
else
set(H.xline,'xdata',[pt(1,1)-xlim,pt(1,1)+xlim]);
set(H.xline,'ydata',[pt(1,2),pt(1,2)]);
set(H.yline,'xdata',[pt(1,1),pt(1,1)]);
set(H.yline,'ydata',[pt(1,2)-ylim,pt(1,2)+ylim]);
end
%-----------------------
%-----------------------