I am using a function and i want to update counter on each function call and use value of that counter for some condition.But every function call counter initialize to zero and if i use counter=counter+1 it always give counter =1 so how to do this?

조회 수: 40 (최근 30일)
The variable counter value should be equal to number of times function call.

채택된 답변

Jan
Jan 2017년 5월 26일
The question might be more clear, if you post the relevant code. The reader cannot guess, what code causes the observed "every function call counter initialize to zero".
Either:
counter = 0;
for k = 1:100
counter = counter + 1;
disp(counter);
end
Or it might be a counter inside a function:
function Y = YourFcn(X)
persistent Counter
if isempty(Counter)
Counter = 0;
end
Counter = Counter + 1;
Y = sin(X + Counter);
Then the Counter is reset by "clear YourFcn".
  댓글 수: 3
Jan
Jan 2017년 5월 27일
It is not clear, what the code should do. A bold guess:
function Avg_SU = request_order(x)
persistent FirstRun
if isempty(FirstRun)
X = 1:14;
FirstRun = false;
else
z = (x == (1:14));
Xr = X(z);
n = numel(Xr);
X(z) = Xr(randperm(n,n));
end
%%some code for request order%%
Avg_SU=sum(avg_su_per_req)/100;
X is not used at all?!
But as long as I do not really undestand, what you want to solve, I would not trust this code.
Vishnubharathi Thirupathi
Vishnubharathi Thirupathi 2023년 3월 23일
Hi, I need to impletment counter within a if condition of a function. eg., if the condition goes into elseif, it should be there max 540s && SOC>=20. Is there any other way to achieve this? because t_reff = 0; makes t_reff = 0 each time, and I always see t_reff =1. I tried with persistant and global but could not rightly implement what I need.
function [I_ref,t] = fcn(t,SOC,P)
t_reff = 0;
I_ref = 0;
%% Operational Limits
% Current Limit
if (t<=1200 && SOC >= 40)
I_ref = -19.25/P;
elseif (t_reff <= 540 && SOC >= 20)
I_ref = -20.25/P;
t_reff = t_reff+1;
else
I_ref = -20.75/P;
end

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

추가 답변 (1개)

MathReallyWorks
MathReallyWorks 2017년 5월 26일
Hello Amit,
Keep your initialization on top of the code (i.e. outside of loop if any).
Check if it is in any loop which is causing it to initialize again.
counter=0
should be above the code (i.e. outside of loop)
and
counter=counter+1
should be inside the loop.
If you want a better answer, attach your code.

카테고리

Help CenterFile Exchange에서 System on Chip (SoC)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by