User Input in MATLAB

User Input

User input can be obtained through the <span>input</span> function, which displays a prompt and waits for the user’s response:

>> x = input('Starting point: ')
Starting point: 0.5
x =
    0.5000

Here, the user responds by entering “0.5”, which is assigned to the variable <span>x</span>. When the additional parameter <span>'s'</span> is used, the input is interpreted as a string:

>> mytitle = input('Plot title: ', 's')
Plot title: Experiment 2
mytitle =
    Experiment 2

<span>ginput</span> function collects data through mouse clicks. The command:

[x,y] = ginput(n)

returns the <span>x</span> and <span>y</span> vectors, containing the coordinates of the next <span>n</span> mouse clicks in the current figure window. If the Enter key is pressed before the <span>n</span>th mouse click, the input will be terminated. <span>ginput</span> can be used to find approximate locations of points on a graph. For example, in the current figure window, use the following command:

[x,y] = ginput(1)

and click on one of the curve intersections. As another example, the program for plotting a Bezier curve can be modified to

% BEZIER_PLOT Plot bezier curve and control polygon.
axis([0 1 0 1])
[x,y] = ginput(4);
P = [x';y'];
hold on
u = 0:.01:1;
umat = [(1-u).^3; 3.*u.*(1-u).^2; 3.*u.^2.*(1-u); u.^3];
Curve = P*umat;
fill(P(1,:),P(2,:),[.8 .8 .8]) % Shaded control polygon.
plot(Curve(1,:),Curve(2,:),'k-','linewidth',2) % Bezier curve.
plot(P(1,:),P(2,:),'o','MarkerFaceColor','k') % Control points.
text(0.35,0.35,'control polygon')
text(0.05,0.3,'P_1')
text(0.25,0.8,'P_2')
text(0.72,0.6,'P_3')
text(0.82,0.1,'P_4')
hold off

Now, the control points are determined by the user’s mouse clicks.

<span>pause</span> command pauses execution until a key is pressed, while <span>pause(n)</span> waits for <span>n</span> seconds before continuing execution. A typical usage is to insert <span>pause</span> commands between a series of plotting commands. Previously, it was also commonly used with the <span>echo</span> command for demonstration scripts, but this usage has been replaced by demonstrations in the Help browser.

Leave a Comment