If loop on ascii code condition not working

15 views (last 30 days)
Can someone explain to me why the following is happening when I try to run this simple code?
word='[HelloKitty|~123]';
letters= length(word);
x= double(word);
i=1:length(x);
if letters < 4 | 65>x(i) | 90<x(i)<97 | x(i)>122
disp ('no!!!!')
end
Here is the ascii code matrix for the inputted word: '[HelloKitty|~123]'
>> x(i)
ans =
Columns 1 through 15
91 72 101 108 108 111 75 105 116 116 121 124 126 49 50
Columns 16 through 17
51 93
Since the word has ascii characters from all ranges (uppercase, lowercase, characters from the 91-96 ascii block, characters and numbers before and after the letter blocks), I'm expecting the IF-loop to show the display message for this word, which does happen.
if letters < 4 | 65>x(i) | 90<x(i)<97 | x(i)>122
disp ('no!!!!')
end
no!!!!
BUT....if I run the if loop with only one of the conditions specified, it doesn't work for all of them (see below).
if letters < 4
disp ('no!!!!')
end
>> if 65>x(i)
disp ('no!!!!')
end
>> if 90<x(i)<97
disp ('no!!!!')
end
no!!!!
>> if x(i)>122
disp ('no!!!!')
end
>>
My question is WHY NOT??? There are characters or numbers in the word that meet each of these conditions, so why do the 65>x(i) condition and the x(i)>122 condition not end up with a display message?

Answers (1)

Walter Roberson
Walter Roberson on 3 Feb 2018
90<x(i)<97
means the same as
((90<x(i))<97)
which first compares x(i) to 90, giving a result of 0 (false) or 1 (true), and then the expression goes on to compare that 0 or 1 to 97.
I seem to be having difficulty finding any computer languages which do permit the syntax you used?
  2 Comments
Matlab_Novice
Matlab_Novice on 3 Feb 2018
Hello Walter, thanks for your response. So are you suggesting the reason the 90-97 condition works is because my syntax is wrong, and technically none of those conditions should be working? If that is the case, how would you write a code where you're asking to check if a word falls within certain ascii code ranges?
Walter Roberson
Walter Roberson on 6 Feb 2018
You can use
90 < x(i) && x(i) < 97
but it would be much more clear to use
ismember(x(i), '[\]^_`')

Sign in to comment.

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!