I have a function below.
As you can see if t==1 I create a vector kk. However, I can not use this kk in the 'else' statement unless I use 'global kk''. Is that correct?
function [ll mm]= ssample(e2,t)
global kk
if t==1
kk=zeros(T,1);
for s=1:T
kk(s) =...;
end
else
for s=t:T
ll =kk(s) ;
end
end
mm=kk;
end

댓글 수: 5

John D'Errico
John D'Errico 2019년 5월 9일
I edited your code to fix the indenting and make it readable.
ektor
ektor 2019년 5월 9일
Am I using correctly the global operator?
Walter Roberson
Walter Roberson 2019년 5월 9일
편집: Walter Roberson 2019년 5월 9일
We have no reason to expect that t will be 1 before it is anything else.
The correct way to use the global operator is mostly to not use it.
I suspect you should be using
persistent kk
if isempty(kk)
... initialize kk here ...
end
ektor
ektor 2019년 5월 9일
I edit my question. t is defined and it starts from t=1. Should I use global?
Walter Roberson
Walter Roberson 2019년 5월 9일
We would need the calling code to be sure that t starts at 1.
Better to avoid the matter, such as the way Matt suggests.

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

 채택된 답변

Matt J
Matt J 2019년 5월 9일

0 개 추천

No, you should not use global. Your code should look like this:
function [ll, mm, kk]= ssample(e2,t,kk)
...
end

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

질문:

2019년 5월 9일

댓글:

2019년 5월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by