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

2 ビュー (過去 30 日間)
Christine
Christine 2023 年 7 月 12 日
編集済み: Stephen23 2023 年 7 月 12 日
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 件のコメント
Stephen23
Stephen23 2023 年 7 月 12 日
編集済み: Stephen23 2023 年 7 月 12 日
"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?

サインインしてコメントする。

回答 (2 件)

Malay Agarwal
Malay Agarwal 2023 年 7 月 12 日
編集済み: Malay Agarwal 2023 年 7 月 12 日
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 2023 年 7 月 12 日
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!

カテゴリ

Help Center および File ExchangeC Shared Library Integration についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by