Trouble with char and doubles in code
Show older comments
I'm trying to write some code that asks a user for two numbers and checks that the second is not less than the first.
If the user enters anything other than a number they should be prompted to try again.
I'm having trouble distinguishing between char and double and I now have an error that I am not sure what it means.
Here is my code:
A = ''; %char
while isempty(str2num(A))
A= input('Please enter a number: ','s');
end
A = str2num(A); %double
B = ''; %char
while true
while isempty(str2num(B)) %char
B= input('Please enter a number: ','s'); %char
end
while ~isempty(str2num(B)) %char
B = str2num(B); %double
if B < A %double
B= input('B less than A, try again: ','s'); %char
else
B = num2str(B); %char
break
end
B = num2str(B); %char
break
end
end
B = str2num(B); %double
%need A and B to be doubles for plotting......
Here is the error:
EDU>> Untitled2
Please enter a number: 3
Please enter a number: 6
Operation terminated by user during int2str (after line 32)
In num2str (line 68)
s = int2str(x); % Enhance the performance
In Untitled2 (line 19)
B = num2str(B); %char
Any help would be much appreciated as Matlab has been outwitting me for the last eleven hours.
Cheers
Steve
Accepted Answer
More Answers (1)
Walter Roberson
on 23 Oct 2013
0 votes
When you get to the "else" of "if B < A", you convert B back into a string and then "break" out of the "while ~isempty" loop. But that leaves you inside the "while true" loop. Which goes through the logic again, converts B to numeric, does the test, hits the else, converts B back to string, breaks the ~isempty loop, stays within the while true loop...
I would also point out that you never test whether A or B are strings that represent numbers. You can do that by testing isnan() of the numeric value. Remember to get a confirmed number for A before you bother getting a confirmed number for B. And remember that once you have two confirmed numbers you are allowed to end the program (after doing the check for which is bigger), so you do not need to infinite loop the whole process.
Categories
Find more on Loops and Conditional Statements 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!