필터 지우기
필터 지우기

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

조회 수: 5 (최근 30일)
sofiane benhamza
sofiane benhamza 2020년 9월 23일
편집: Adam Danz 2020년 9월 23일
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

채택된 답변

Adam Danz
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.
  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
sofiane benhamza
sofiane benhamza 2020년 9월 23일
편집: sofiane benhamza 2020년 9월 23일
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
Adam Danz
Adam Danz 2020년 9월 23일
편집: Adam Danz 2020년 9월 23일
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...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by