str in a IF statement, PLEASE HELP
2 views (last 30 days)
Show older comments
Thats what I asked to do.
This is my code so far. But its not working for the str and complex part. Can anyone kindly help me?
p = input('To play the game, enter a shooting angle between -90 and 90 degree: ');
for i = 1 : p
if p(i) <= -90 || p(i) >= 90
disp('Enter a real number between -90 and 90 degree!!!');
break
elseif p(i) == 'str'
disp('Enter a real number between (-90~90) rather than string');
break
elseif p(i) == 'complex'
disp('Enter a real number between (-90~90) rather than any complex number')
break
end
end
0 Comments
Accepted Answer
sruthi gundeti
on 12 Sep 2020
Hi ,
Try Isstr to detect a string and isreal to detect a real number or complex number
for i = 1 : p
if p(i) <= -90 || p(i) >= 90
disp('Enter a real number between -90 and 90 degree!!!');
break
elseif isstr(p(i))
disp('Enter a real number between (-90~90) rather than string');
break
elseif isreal(p(i))==0
disp('Enter a real number between (-90~90) rather than any complex number')
break
end
end
2 Comments
Adam Danz
on 12 Sep 2020
Edited: Adam Danz
on 14 Sep 2020
This set of tests is not complete and the loop is incorrect. For example, if the user enters the number 10, why would the loop run 10 times? That's what this loop is doing. If the user enters a negative number, the loop doesn't run at all.
Maybe sruthi intended to write
for i = 1 : numel(p)
but it's still not clear why there needs to be a loop in the first place since the instructions are to enter a single value.
Matlab offers much more robust tests for input validation that can be done in a single line of code.
More Answers (1)
Adam Danz
on 12 Sep 2020
Edited: Adam Danz
on 12 Sep 2020
- Why do you have a loop when the instructions ask for a single value?
- The use of break usually indicates inefficient coding. Again, I don't see a reason to have a for-loop to begin with. Even with the loop. I don't understand why you would break after the first iteration.
- Instead of using conditional statements to confirm that the user entered a valid response, use input validation such as validateattributes (doc).
validateattributes(p,{'numeric'},{'scalar','>=',-90,'<=',90},mfilename,'input')
Test some results
% When p is a string
p = '5';
ERROR:
Expected input to be one of these types:
double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64
% When p contains more than 1 value
p = [1 2];
ERROR:
Expected input to be a scalar.
% When p is a value out of range
p = -180;
ERROR:
Expected input to be a scalar with value >= -90.
p = 100;
ERROR
Expected input to be a scalar with value <= 90.
0 Comments
See Also
Categories
Find more on Characters and Strings 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!