Azzera filtri
Azzera filtri

write a recursive palindrome function but the error is always not enough input arguments

1 visualizzazione (ultimi 30 giorni)
function p=palindrome(n)
if length(n)==1
p==true
elseif n(1:end)==palindrome(end:-1:1)
p=true
else p=false
end
i am very new to matlab (started a week ago) and tried this code and the error is always not enough input arguments i tried searching the meaning but didn't understand it fully and i don't know how to fix it
  1 Commento
Stephen23
Stephen23 il 12 Lug 2023
Modificato: Stephen23 il 12 Lug 2023
"write a recursive palindrome function..."
You created a function named PALINDROME, which accepts one input argument:
function p=palindrome(n)
Then later you call the function recursively:
.. palindrome(end:-1:1)
But what is END supposed to refer to? It looks like you are trying to use END to index into a vector... but what vector?

Accedi per commentare.

Risposte (2)

Malay Agarwal
Malay Agarwal il 12 Lug 2023
Modificato: Malay Agarwal il 12 Lug 2023
Please use the following function. Your code is missing an end to end the function defintion. There are also logical errors in the code, like the condition used in the elseif. Note that you need to pass n as a character vector.
n = 'abba';
palindrome(n)
ans = logical
1
n = 'abc';
palindrome(n)
ans = logical
0
function p = palindrome(n)
% If empty or a single character, trivial palindrome
if length(n) <= 1
p = true;
% Compare the first and last characters, and recursively compare the
% rest of the string
elseif n(1) == n(end) && palindrome(n(2:end-1))
p = true;
else
p = false;
end
end

Swapnil Tatiya
Swapnil Tatiya il 12 Lug 2023
I'm guessing the error shows up because you're passing an integer (n) as an argument and not an array of integers and you're assuming the digits to be different indices of that integer,but that's not the case in MATLAB.
The following code should help you in knowing whether an integer or a string is a palindrome:
function p=palindrome(n)
x=string(n);
if isequal(x,reverse(x))
p=true;
else
p=false;
end
end
Hope this helps!

Categorie

Scopri di più su Characters and Strings 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!

Translated by