write a recursive palindrome function but the error is always not enough input arguments
조회 수: 2 (최근 30일)
이전 댓글 표시
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
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
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)
n = 'abc';
palindrome(n)
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
댓글 수: 0
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!
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 C Shared Library Integration에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!