- 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.
- You probably want to reset output back to 0 after input reaches 0. In that case, you can make this change,
how can i declare a variable in a function for the first time only ,
7 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Adam Danz
2020-9-23
编辑:Adam Danz
2020-9-23
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.
if input==0
%output=output; % What's this ??
h = output;
output = 0;
else ...
4 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!