MATLAB: Getting points with ginput from image and plotting simultaneously each selected point

ginputplotpoint

I am trying to select an unlimited number of points from an image ([x,y] = ginput), and each time I select a point I want to plot it, so I can have a real time reference of each point I get.
I have tried with this code, but I don't get it to work.
Here is the code I use:
I = imread('cameraman.tif'); % example
imshow(I);
axis on;
button = 1;
i = 1;
n = 1;
while button(i) == 1
[x,y, button] = ginput(1)
x_n(n) = x(i); % save all points you continue getting
x_n(n) = y(i);
hold on
plot(x(i),y(i),'r')
drawnow
n=n+1;
end
I have read some answers where they use for loops with a limited number of points to be selected, but I must have an unlimited number of points, that's why I use as loop condition the pressed button.
Thank you for any help in advance.

Best Answer

n = 0;
while true
[x, y, button] = ginput(1);
if isempty(x) || button(1) == 1; break; end
n = n+1;
x_n(n) = x(1); % save all points you continue getting
y_n(n) = y(1);
hold on
plot(x(1), y(1), 'r')
drawnow
end