str in a IF statement, PLEASE HELP
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Thats what I asked to do.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/359587/image.png)
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 Commenti
Risposta accettata
sruthi gundeti
il 12 Set 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 Commenti
Adam Danz
il 12 Set 2020
Modificato: Adam Danz
il 14 Set 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.
Più risposte (1)
Adam Danz
il 12 Set 2020
Modificato: Adam Danz
il 12 Set 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 Commenti
Vedere anche
Categorie
Scopri di più su Numeric Types in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!