Display a message only one time in a recursion containing a for loop

Consider this simple code
a=[1 1 0 1];
recursion(a)
with
function a=recursion(a)
if isempty(a)
disp('a does not contain 0')
else
for i=1:numel(a)
if a(1)==0
disp('a contains 0')
return
end
a=a(2:end);
recursion(a);
end
end
end
Don't focus on the aim of the code (of course the job could be done in 1 line or 2) but on the output
a contains 0
a contains 0
a contains 0
a contains 0
ans =
0 1
Is it possibile to output the message "a contains 0" only one time AND then to output the modified vector "a" ? i.e. is it possibile to have this output
a contains 0
ans =
0 1

 Accepted Answer

Do not have recursion return a, since the changed value is not used. Instead, have it return a status as to whether it encountered a 0. Check the output and if set then break out the the loop and return 1. Only return 0 if you get to the end of the loop without a 0.

6 Comments

Thanks for the answer, you mean this?
a=[1 1 0 1];
found=recursion(a);
if found
disp('a contains 0')
else
disp('a doesn''t contain 0')
end
with
function found=recursion(a)
if isempty(a)
found=0;
else
for i=1:numel(a)
if a(1)==0
found=1;
return
end
a=a(2:end);
found=recursion(a);
end
end
end
Change
found=recursion(a);
to
if recusion(a)
found = 1;
break;
end
Sorry I don't understand, in that way the output argument will not be assigned, right?
Using:
find=recursion(a);
if find
disp('a contains 0')
else
disp('a don''t contain 0')
end
function found=recursion(a)
if isempty(a)
found=0;
else
for i=1:numel(a)
if a(1)==0
found=1;
return
end
a=a(2:end);
if recursion(a)
found = 1;
break;
end
end
end
end
with a=[1 1 0 1] it prints
a contains 0
but whit a=[1 1 1 1] it says
Output argument "found" (and maybe
others) not assigned during call to
"recursion".
EDIT
maybe this one is even better
a=[1 1 0 1];
found=recursion(a,0);
if found
disp('a contains 0')
else
disp('a don''t contain 0')
end
with
function found=recursion(a,found)
for i=1:numel(a)
found=a(1)==0;
if found
return
end
a=a(2:end);
recursion(a);
end
end
function found=recursion(a,found)
for i=1:numel(a)
found=a(1)==0;
if found
return
end
a=a(2:end);
found = recursion(a);
if found; break; end
end
end
Ok many thanks, why you put another if after the recursion call? Moreover, should I also change "return" with "break" in the first if ?
The "break" could be changed to return. The idea is that as soon as you see it found you do not need to examine the rest of a in the for loop.

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!