Find the max of a vector recursive
조회 수: 21 (최근 30일)
이전 댓글 표시
Hello all,
Im trying to find the max value of an element in a vector, for learning purposes Ineed to do this recursive. I have been trying this all over again but something goes terribly worng. Could anybody point out to me what I am doing wrong? Thanks in advance.
function output = recursive_max(input)
%%Write a function called recursive_max that finds the maximum element in a
%%vector. You are not allowed to use loops or any built-in functions other
%%than length. The sole output argument is the maximum value in the input
%%vector. Hint: the maximum value of a vector is the larger of its first
%%element and the maximum of the rest of the elements.
l = length(input);
if l == 1
output = recursive_max(input(end))
else
if input(end-1) >= input(end)
input(end) = [];
recursive_max(input);
end
input(end-1) = []
end
end
댓글 수: 0
채택된 답변
John D'Errico
2021년 5월 13일
편집: John D'Errico
2021년 5월 13일
This is a godawful problem to solve using recursive coding. Why? Suppose your vector has a million elements in it. Then this code will need to make 1 MILLION nested, recursive calls. That will be 1 MILLION separate function workspaces, all of which will be actiuve until the final call allows all of those recursive calls to unwind. 1 MILLION calls. Can you possibly want to do that? NO! Not in a million years.
Yes, I understand this is homework, and you need to do as directed. What I want you to understand is why that is such a bad idea for when you start writing code of your own.
Regardless, you made a (barely) credible start to your task, though your code is not really that close to being workable. What did you do wrong?
A recursive code will need to have an end condition. Your code has that, to deal with the problem when your vector has length 1. For longer vectors, You will compare the first element to recursive_max of the rest.
By the way, not needing to use other built-in functions means you cannot use max, but it also means you cannot even use the > comparison operator. That is in fact a built-in function. Anyway, your code should look most simply like that below:
x = [1 3 2 5 6 2];
recursive_max(x)
function output = recursive_max(input)
if length(input) == 1
output = input;
else
output = recursive_max(input(2:end));
if input(1) > output
output = input(1);
end
end
end
So think about it. Will this work? Of course. Do you want to use that code in any rational form? YE GOD NO!
댓글 수: 2
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!