How to understand a recursion problem? and how to get its solution value?

4 visualizaciones (últimos 30 días)
John
John el 5 de Mzo. de 2016
Editada: Stephen23 el 6 de Mzo. de 2016
Hi guys,
i implemented a quite large code recursively.... the goal is to improve a tour by adding clients until no client is permitted anymore. The abstract pseudocode works like this:
function [ best_tour ] = improvement( tour )
if ~isempty(next_client)
x=next_client(best) %client out of a set of clients chosen with a specific criteria
tour_temp=[tour,x_index_in_tour]; %integration into the tour at a specific index
if tour fulfills_constraints
[ best_tour ] = improvement( tour_temp )
next_client=next_client(next_client~=next_client(best)) %Remove client from set of clients
else
%Remove insertion index for this chosen client
[ best_tour ] = improvement( tour ) %Start again improvement and pick next best client from the set of clients
%It can even be the same client with another index
end
else
return best_tour
end
I the code works well which means that a given parameter "tour" is extended to a good solution until no other client can be integrated into this tour without violating constraints. lets call the solution "tour*"
The Problem is that i cannot give the solution back to my main programm!!! i always get back the same solution "tour" that i put in as a parameter although i can see by debugging that there has been created a much better one "tour*"... The strange thing is that when i continue debugging after having got the tour "tour*" then this tour "tour*" is reduced again to the given parameter "tour"...it takes exaclty the same number of steps it took to get from "tour" to "tour*"...so output is the same as the input altough during execution there has been found a much bette rsolution?
i know it has to do with the recursion depth but i dont understand it:( i tried breaking it down to an easy problem like this:
function [ y ] = Improvement_test( x )
y=x
x=x+5;
if y<42
y=improvement_test(x)
end
end
when i execute it with x=20 i get the results: Why is there this 6 times 45 in the end? i just want to have the final solution once and as soon as it is reached i want to break from the rekursion...would be glad to be explained this weird behaviour.
Improvement_test( 20 )
y =
20
y =
25
y =
30
y =
35
y =
40
y =
45
y =
45
y =
45
y =
45
y =
45
y =
45
ans =
45
>>
best regards, John
  1 comentario
Walter Roberson
Walter Roberson el 6 de Mzo. de 2016
Note: MATLAB's return is not to be followed by a value . You cannot say what value is to be returned: the value of the function will be according to whatever was set for the output variables.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by