Value of variable after passing one simulation cycle

2 次查看(过去 30 天)
Hi guys,
I have a pretty straightforward question I believe. Say i am applying a code using a MATLAB function block into my Simulink. I have a code which looks like this. If i run this code, will my D be reset to 0 every simulation cycle when it runs the code again from the beginning? Or my D output will remain as what I have set from the If statements shown. Same question goes for N. I plan to set N as some sort of delay in the form of a 'counter' to ensure that each of the D values I set will be fed into my simulation because at this point (my hypothesis), my prev codes give only one duty cycle probably because the code ran too fast? Dont really know the concept of simulation cycle between MATLAB function blocks with Simulink.
function D = BAT(P)
%% declare all variables %%
DPold = [0.2;0.4;0.6;0.8];
D = 0;
N = 0;
if N==0
D = DPold(1);
end
if N==1000
Pold(1) = P;
end
if N==1001
D = DPold(2);
end
if N==2000
Pold(2) = P;
end
if N==2001
D = DPold(3);
end
if N==3000
Pold(3) = P;
end
if N==3001
D = DPold(4);
end
if N==4000
Pold(4) = P;
end
N = N+1;
end

采纳的回答

Raj
Raj 2019-7-15
Ok this is not going to serve your purpose. There is a reason its called simulation Cycle/Cycle time. The whole model (including function blocks) get executed once in each cycle and this is repeated again in next cycle and so on. So your variables D and N will always get reinitialized to zero in each simulation cycle. Now the problem is not reinitialization of D because it gets reassigned depending on value of N as per if-else conditions. But because of the reinitialization of N to zero, the only condition that will pass in each cycle is
if N==0
D = DPold(1);
end
so in the end you will get only one value of D throughout your simulation which will be D=DPold(1)=0.2
"I plan to set N as some sort of delay in the form of a 'counter' to ensure that each of the D values I set will be fed into my simulation"- From this statement I assume that all you want to do is output different values of D in your simulation as a function of time. Not sure what is 'P' and what 'Pold' is doing in the function. One way you can do this is to give clock as an input to your function block. You can define your function something like this:
function D = BAT(time)
D=0; %initlalize
%% declare all variables %%
DPold = [0.2;0.4;0.6;0.8];
if time<=2
D = DPold(1); % output first value till 2 sec
elseif time>2 && time<=4
D = DPold(2); % output second value after 2 sec till 4 sec
elseif time<4 && time<=6
D = DPold(3);% output third value after 4 sec till 6 sec
elseif time<6 && time<=8
D = DPold(4);% output fourth value after 6 sec till 8 sec
end
end
Correct me if my understanding of your problem statement is not right.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Outputs 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by