Recursive nested function gives different result on first run

I have a recursive function that is nested in my main function and when assigning its output to some variable it gives a different result (for certain inputs). Here's an example showing the behaviour
function arr = foo( )
% clear all % makes it give the same (possibly wrong) result every time
function arrB = foorecurse( currIds )
disp(currIds) % correct
disp(cellfoo{currIds(1)}) % correct
fprintf('---------\n')
if length(currIds) == 1
arrB = cellfoo{currIds}
else
arrB = [cellfoo{currIds(1)} ; foorecurse(currIds(2:end))]
end
end
cellfoo = { eye(2), [0 1 ; 1 0], [0 -i ; i 0], [1 0 ; 0 -1] };
% foorecurse([2 3 2]) % not assigning the output to any variable "fixes" it
arr = foorecurse([2 3 2]) % gives a column of cellfoo{[3 3 2]} first time it's run
% arr = foorecurse([2 1 2]) % this is fine
end
I have not tested it on another machine. I am at a total loss as to what could be happening. I know there's a way to achieve the same thing in many other ways (and they work) but for the sake of understanding what ML does, can anyone figure this out?

 Accepted Answer

I think it's a parsing bug and I encourage you to report it to Tech Support.
Initially, I supposed that it's some hazard of mixing recursive calls with concatentation operations, but this variation seems to work just fine,
function arrB = foorecurse( currIds )
if length(currIds)==1
arrB = cellfoo{currIds};
else
arrB = [foorecurse(currIds(1)) ; foorecurse(currIds(2:end))];
end
end

3 Comments

Well spotted, makes it even more bizarre! I reported it to Tech Support, will post any updates.
You were right, it is a bug. I heard from the Technical Support:
"[T]he error that you face is a bug due to JIT implementation. However, it does not exist from the R2015b release of MATLAB. [...] [Y]ou could add the following line [to] turn off the JIT for the duration of the offending function."
feature scopedaccelenablement off

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!