write a recursive palindrome function but the error is always not enough input arguments
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Stephen23
el 12 de Jul. de 2023
Editada: Stephen23
el 12 de Jul. de 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?
Respuestas (2)
Malay Agarwal
el 12 de Jul. de 2023
Editada: Malay Agarwal
el 12 de Jul. de 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)
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 comentarios
Swapnil Tatiya
el 12 de Jul. de 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!
0 comentarios
Ver también
Categorías
Más información sobre C Shared Library Integration en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!