问题
I want to make a little script in which I can systematically ananlyse a lot of matlab plots. With the script I should be able to click on some points in the graph and the script then stores these values. I have now that the callback function has the coordinates, but I want these values in the main file to store them. But the set function can't receive values from a function. How can I create another construction to avoid this? [x,y] = set(f,'ButtonDownFcn',{@Click_CallBack a}); doesn't work unfortunalty..
function process_plot()
dataset_dia = input('diameter?')
dataset_length = input('length?')
h = gcf;
a = gca;
f =get(gca,'Children');
set(h, 'Pointer', 'fullcrosshair');
set(f,'ButtonDownFcn',{@Click_CallBack a});
save(strcat(dataset_dia, '.mat'), x, y);
end
Function that extracts the coordinates from the plot:
function [x, y]= Click_CallBack(h,e,a)
point = get(a,'CurrentPoint'); x = point(1);
y = point(4);
fprintf(1,'X,Y = %.2f,%.2f\n',x,y);
end
回答1:
You could do something like the following. Left click to store points in user data then right click when finished selecting to write them to a MAT file.
function process_plot()
f =get(gca,'Children');
set(gcf, 'Pointer', 'fullcrosshair');
set(f,'ButtonDownFcn',{@Click_CallBack gca});
function [x, y]= Click_CallBack(h,e,a)
userData = get(a,'userData'); %Store x,y in axis userData
switch get(ancestor(a,'figure'),'SelectionType')
case 'normal' %left click
point = get(a,'CurrentPoint');
userData(end+1,:) = [point(1,1) point(1,2)];
set(a,'userData',userData)
fprintf(1,'X,Y = %.2f,%.2f\n',point(1,1),point(1,2));
otherwise %alternate click
% Reset figure pointer
set(ancestor(a,'figure'), 'Pointer','arrow');
%Clear button down fcn to prevent errors later
set(get(gca,'Children'),'ButtonDownFcn',[]);
%Wipe out userData
set(a,'userData',[]);
x = userData(:,1);
y = userData(:,2);
save('myMatFile', 'x', 'y'); %Save to MAT file ... replace name
end
That is of course if you are not using the axis user data for something else. Also note tha the current point retrieved during the button press will not actually be in your plotted data set. It is just the cursors current position over your drawn lines. If you want actual points in your plotted lines you will have to search within your data for the closest point to the retrieved cursor position.
来源:https://stackoverflow.com/questions/8702342/matlab-how-to-make-a-set-callback-return-values