how can i declare a variable in a function for the first time only ,

function h=src(input) %example
output=0 %here i won't output to be declared again when matlab gonna calcul src(input-1)
if input==0
output=output
else
output= output +1
src(input-1)
end

 Accepted Answer

I think this is what you're looking for,
function h=src(input)
persistent output %%%%%%%%
if isempty(output) %%
output = 0; %%
end %%%%%%%%
if input==0
%output=output; % What's this ??
% Do nothing
else
output= output + 1;
src(input-1);
end
h = output; % assign output!
However, this still has problems.
  1. What if user enters src(-1)? What about src(.9)? The input will never reach 0 and you'll run out of memory. To prevent the user from entering negative or non-scalar values, use an argument validation function.
  2. You probably want to reset output back to 0 after input reaches 0. In that case, you can make this change,
if input==0
%output=output; % What's this ??
h = output;
output = 0;
else ...

4 Comments

it wasn't important to me , i'd just wrote it ,i thank you very mush but this code is my problem
it should computes the sum of digits of a positive number which is already given (ex: 12345=>1+2+3+4+5=15) , and it must containt recursive function, and i shouldn't worry about the input , but i couldn't understand , why it didn't
function h=src(input) %input is already given
h=0;output=0; %needed for calculations
if input == 0 % 0 gonna give 0
Output=output ;
s(Output) %to display the Output in screen , 3rd function
return
else
f(input) % to the second function
end
end
function z=f(input)
z=input*.1 %{ i'm trying to do it by this way ,
if input=214 , > z=214*.1=21.4 , a=(z-fix(z))*10=(21.4-21)*10 = 4
t=0; t will contain the final result t=t+a this works if z~=fix(x) (case when
a=0 , that's why i add if
if z==fix(z)
t=t+z;
else
a=(z-fix(z))*10;
t=t+a; %t should contain the final result
Output=t;
input=fix(z);
src(input) %return to the main function i there is more numbre 21 will be 2.1 and like this
t=t+1 ............;;t=t+2
end
end
function ss=s(k) %this one is just to display the result if found , but mt code still have problems and i
can't find them
ss=0;
display(k)
end
So the input is 12345 or is it [1,2,3,4,5]?
they said that it's one positive number , and i'm not allowed to use loops or str2num , i wish that it was a vector
There are already lots of solutions for this within this forum.
Search the forum for phrases like
  • Convert integer to vector
  • Convert scalar to vector
  • 123 to 1 2 3
etc...

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!