Kevin Klopfenstein <kklopfenstein@gmail.com> wrote in message <25723403.1234752825352.JavaMail.jakarta@nitrogen.mathforum.org>...
> I am extremely rusty on recursion and I got this to work as a void recursive function in C++ and I was hoping, since I have almost no prior knowledge of MATLAB, if somebody could enlighten me as to why this is occurring.
>
> Here is the code of my recursive function, bearing in mind that x is an array, c is an array, and iterations is supposed to count the total number of computations the recursive function makes:
>
> function sum = trap(x,c,count,k,sum,iterations)
> n=2;
> for (p=0:.5:1)
> if count<k
> x(count) = p;
> trap(x, c, count+1, k, sum, iterations);
> else
> x(count) = p;
> for (i=1:k)
> if ((x(i) == 0)(x(i) == 1))
> c(i) = (1/(2*n));
> else
> c(i) = (1/n);
> end
> end
> partsum = 0;
> for (i=1:k)
> partsum = partsum + (x(i)/n).^2;
> end
> for (i=1:k)
> partsum = partsum .* c(i);
> end
> iterations = iterations + 1;
> sum = sum + partsum;
> end
> end
>
> When i call this function, it seems to reset the values of the variables when I recursively call this function. If I print the value of the iterations variable it displays 1,2,3 consecutively and then resets. Apparently all the variables are resetting because my summation is wrong at the end as well.
>
> Thanks for the help
Several things wrong here. I don't think you
appreciate how functions work in MATLAB, nor
how they return arguments from their workspaces.
1. DON'T name a variable sum. You will be sorry
when you want to use the function sum in your
code.
2. When you call the function trap, you supply no
return argument. When each recursive call exits, it
dumps the parameters in its workspace into the bit
bucket. So iterations disappears. It is only an input
argument, not an output.
3. The output sum variable is not summed either,
since that value just gets dumped onto the
command line.
Take a look at my partitions code on the FEX for
a nicely recursive function.
http://www.mathworks.com/matlabcentral/fileexchange/12009
John
