MATLAB: How to enforce user to use the right letter

inputinput validationstringwhile loop

The code I'm currently trying to build depends on the user using the correct letters, corresponing x and y. So what I want to do is to create an error-message for when the user does not use x & y, and then prompts him to try again. I have this so far:
coord=input('Enter an x and a y coordinate on the form x3 y4: ','s');
while sum(isletter(coord))~=2
coord=input('Please only write one letter for x and y, try again: ','s');
end
while strfind(coord,'x')>strfind(coord,'y')
coord=input('Please enter x before y, try again: ','s');
end
coord=strtrim(coord); %eliminates blanks before and after
[xval,yval]=strtok(coord); %Splits coord in two
[xval,~]=strtok(xval,'x'); %gives only the number in variable
[yval,~]=strtok(strtrim(yval),'y');
pause(1)
% while strfind(coord,'x')==[] && strfind(coord,'y')==[]
% coord=input('Please use the letters x and y accordingly, try again: ','s');
% end
fprintf('You have chosen the coordinates (%s,%s)\n',xval,yval)
x=str2double(xval);
y=str2double(yval);
plot(x,y,'ko','MarkerFaceColor','k')
grid on
I want the commented part to work somehow. I want the program to be able to recognize the letters in the input and determine if they are the right ones basically.
Any suggestions?

Best Answer

input() method
One way is to continually ask the user for input until they get it right. This is done in a while loop. A regular expression tests whether the response was in the form of x# y#
  • with any amount of space between x# and y#
  • allowing for negative numbers such as x-2 y3
  • allowing for decimal places such as x0.52 y2.14 (will not allow x.52; must have a leading 0)
check = false;
while ~check
coord=input('Enter an x and a y coordinate on the form x3 y4: ','s');
check = ~isempty(regexp(coord,'^x[+-]?\d+\.?\d* +y[+-]?\d+\.?\d*$','once'));
end
inputdlg() method
A better, more controlled method might be to use an input dialog box as demonstrated below.
response = inputdlg({'Enter an x coordinate','Enter a y coordinate'}, mfilename, [1 20; 1 20],{'0';'0'});
x = str2double(response{1});
y = str2double(response{2});