Variables scope issue with nested functions and callback

1 view (last 30 days)
I'm having an issue about variable scope in my function. (a customized ginput). I think the solution is simple, but after numerous test and research, I'm still not able to fix it. All the algorithm seems to work. I get at the end of the ginput2 function the matrix zone I want, but the variable zone in the main function doesn't change its value, even though I use nested functions.
How can I fix it ?
Thanks
Here the code:
function zone=getzone1_2b(matrice,h2)
% Determine the points inside a polygone (zone) defined by the coordinates clicked by the user on a matrice plotted in a figure h2. zone is a matrix the same size of matrice, with zone(x,y)=1 for a point inside the polygone, zone(x,y)=0 otherwise.
zone=zeros(size(matrice)); i=1; x=[]; y=[]; ht=[];
set(h2,'WindowButtonDownFcn',@ginput2); set(h2,'WindowButtonMotionFcn',@dispcoor);
% get coordinates of the points clicked by users
function ginput2(src,eventdata)
%Left click on the mouse is used to get the user click coordinates or to erase it if it was already clicked
if strcmp(get(src,'SelectionType'),'normal')
cp = get(gca,'CurrentPoint');
a=round(cp(1,1));
b=round(cp(1,2));
iseq=find(x==a & y==b);
if isempty(iseq)
x(i)=a;
y(i)=b;
ha(i)=plot(x(i),y(i),'o','MarkerFaceColor','k','MarkerSize',10);
i=i+1;
else
x(iseq)=[];
y(iseq)=[];
delete(ha(iseq));
i=i-1;
end;
end;
% If the right button on the mouse is pressed, stop the acquisition and determine the matrix zone
if strcmp(get(src,'SelectionType'),'alt')
n=length(x);
% One point
if n==1
zone(x,y)=1;
end;
% For a line
if n==2
if y(1)==y(2)
zone(min(x(1),x(2)):max(x(1),x(2)),y(1))=1;
elseif x(1)==x(2)
zone(x(1),min(y(1),y(2)):max(y(1),y(2)))=1;
else
p=polyfit(x,y,1);
p=round(p);
if abs(p(1))==1
xa=[min(x(1),x(2)):max(x(1),x(2))];
ya=xa*p(1)+p(2);
B=sub2ind(size(matrice.noeud),xa,ya);
zone(B)=1;
else
h = msgbox('Ligne non prise en compte','Erreur','error');
end;
end;
end;
% polygon
if n>2
zone=inpolygon(matrice.i,matrice.j,x,y);
end;
% Stop acquisition
set(h2,'WindowButtonDownFcn','');
set(h2,'WindowButtonMotionFcn','');
end;
end
% display the coordinates of the cursor
function dispcoor(src,eventdata) delete(ht); set(src,'pointer','crosshair'); cpt = get(gca,'CurrentPoint'); xt=round(cpt(1,1)); yt=round(cpt(1,2)); ht=text(cpt(1,1),cpt(1,2),['x = ' num2str(xt) ', y = ',num2str(yt)],'BackgroundColor',[1 1 1]) ; end end

Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!