# How to create a function that checks if a word is a palindrome?

14 visualizzazioni (ultimi 30 giorni)
Luqas Lundahl il 13 Apr 2022
Commentato: Luqas Lundahl il 13 Apr 2022
Hello!
I want to create a function that checks if a word is a palindrome (a word that is the same when its read left to right as it is right to left)
function P=palindrome(V)
P=palindrome(V(2:end-1));
if V(1)==V(end)
P=palindrome(V(2:end));
P=true;
elseif numel(V)==1
P=false;
end
end
I keep getting errors that i dont have enough input arguments. Any fixes?
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

David Hill il 13 Apr 2022
x='racecar';
isequal(x,flip(x));
##### 3 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
David Hill il 13 Apr 2022
Modificato: David Hill il 13 Apr 2022
function P=palindrome(V)
if numel(V)==1||isempty(V)
P=1;
elseif V(1)==V(end)
P=palindrome(V(2:end-1));
else
P=0;
end
Luqas Lundahl il 13 Apr 2022
thank you!

Accedi per commentare.

### Più risposte (1)

Steven Lord il 13 Apr 2022
A recursive approach, like you've tried to implement, can work but one important aspect of recursion is the base case. This is the case for which you don't recursively call the function. Let's look at your function and think about how it works.
function P=palindrome(V)
P=palindrome(V(2:end-1));
So you (the user) calls the palindrome function.
The palindrome function extracts the part of the input without the first and last element then palindrome (the function) calls palindrome.
The palindrome function extracts the part of the input without the first and last element then palindrome (the function) calls palindrome.
The palindrome function extracts the part of the input without the first and last element then palindrome (the function) calls palindrome.
...
What's your base case? When does this chain of palindrome calling palindrome stop?
I suggest you take a few examples and work through them manually with pencil and paper. Write out the steps you perform to and what tests or decisions you make during the process of identifying whether or not these words or phrases are palindromes. From that see if you can identify a base case that you can detect to break out of the calling chain.
candidates = {'racecar', 'racebar', 'abba', 'palindrome', 'q', ''}
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Luqas Lundahl il 13 Apr 2022
will give it a shot! thank you!

Accedi per commentare.

### Categorie

Scopri di più su MATLAB in Help Center e File Exchange

R2021b

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by