I'm trying to create a code that determines whether a word (or phrase) is a palindrome. The code only needs to look at the actual letters within the input string, but I'm not sure how to do that.
Ältere Kommentare anzeigen
The jist of the problem is to create a function that determines whether a string input is a palindrome by returning the logical true or false. The function needs to disregard any non-letter (i.e. punctuation, spaces, capitalization, etc.), but I'm not sure how to do this.
Here is my code:
function palindrome = hw4_problem2(v)
palindrome = true;
l = lower(v);
n = length(v);
if mod(n, 2) == 0
for ii = 1:n
for jj = n:-1:1
if l(ii) ~= l(jj)
palindrome = false;
else
palindrome = true;
end
end
end
end
end
I was able to use "lower" to get everything into lower letter form, but how do I disregard nonletters? Thanks.
Akzeptierte Antwort
Weitere Antworten (2)
Guillaume
am 18 Mär. 2020
1 Stimme
4 Kommentare
James Metz
am 18 Mär. 2020
Guillaume
am 18 Mär. 2020
"This operator converts the string to a vector of logical values"
Yes, and you can use the logical vector as an index into your char vector (not string) to discard the non-letters:
>> str = 'abc12cba34';
>> str(isstrprop(str, 'alpha'))
ans =
'abccba'
As demonstrated in the very first example of the doc I linked to.
James Metz
am 18 Mär. 2020
Bearbeitet: James Metz
am 18 Mär. 2020
Steven Lord
am 18 Mär. 2020
That checks each element of m against each element of m, but then throws away each result in turn as it checks the next pair of elements. This is only really checking the last element (ii equal to n) and the first element (jj equal to 1.)
You don't want that; you only want to check each element against the corresponding element "at the other end" of m. You only need one for loop, but you do need to stop the loop or treat the value of palindrome as somewhat "sticky" (once you fail one check and know that the string is not a palindrome, no future check can undo that failure and make it a palindrome again.)
The Tips on the documentation page for the for keyword may be of use to you, as might the functions any, all, and, and/or or. Of if the assignment doesn't require you to use a loop, see John D'Errico's answer.
James Metz
am 18 Mär. 2020
Kategorien
Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!