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

2 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 12 Jul 2023
Edited: Stephen23 on 12 Jul 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?

Sign in to comment.

Answers (2)

Malay Agarwal
Malay Agarwal on 12 Jul 2023
Edited: Malay Agarwal on 12 Jul 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 on 12 Jul 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!

Categories

Find more on C Shared Library Integration 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!