How to perform a for loop and if statements with series of conditions?
1 回表示 (過去 30 日間)
古いコメントを表示
Please could you check this code to see if it represents what I am trying to achieve? I feel like I've done everything right, but I'm not getting the result that I need.
Normally gex(t+1) = gex(t) * exp (-0.02)
But anytime I reach t = a number in t_US, gex(t) = gex(t) + 1.2
Anytime, I reach t = a number in t_CS, gex(t) = gex(t) + gCS, where gCS is a value that changes based on these conditions:
- Everytime V(t) > -54, gCS increases by gCS = gCS + (y) . For this function, the max value of gCS must be 1.2
- Everytime t is a number in t_CS, gCS decreases by gCS = gCS + (x). For this function, the min value of gCS must be 0
The initial gex is 0, and the initial gCS is 0.
timeframe = 0: 0.1 : 1000;
t_US = 101: 100 : 601;
t_CS = 90: 100: 190;
V = zeros (1, length(timeframe));
gex = zeros (1, length(timeframe));
V(1) = -70;
gex(1) = 0;
gCS = 0;
dTime_LTP = 0; %a variable that increases with time, and resets to zero anytime t is a number in t_US
dTime_LTD = 0; % a variable that increases with time, and resets to zero anytime V(t) > -54
for t = 1 : length(timeframe) -1
gex(t + 1) = (gex(t) * exp (-dTime/Tex)); %normal formula for gex
if ismember( t, t_CS)
dTime_LTP = 0; %resets to zero because t is a t_CS
gCS = gCS + (A_LTD * exp(-dTime_LTD/ 35));
if gCS < 0
gCS = 0;
end
end
if V(t)> -54
dTime_LTD = 0;
gCS = gCS + (A_LTP * exp(-dTime_LTP/ 25));
if gCS > 1.2
gCS = 1.2;
end
end
if ismember(t, t_US)
gex(t) = gex(t) + 1.2;
end
if ismember( t, t_CS)
gex(t) = gex(t)+ gCS;
end
%series of functions that lead up to the parameters I use to calculate V(t+1)
V(t+1) = E + ((V(t) - E)* exp(- dTime/ timeConst));
dTime_LTP = dTime_LTP + dTime; %increases with time as we go round the loop
dTime_LTD = dTime_LTD + dTime;
end
4 件のコメント
Achin Gupta
2019 年 2 月 27 日
編集済み: Achin Gupta
2019 年 2 月 27 日
Okay.
I recommend running your code on paper and see if it behaves the way you want it to. I say that because multiple if conditions, as you have placed, can easily do unintended actions on participating variables.
In your place, I would make sure that my variables get updated as I want them to. Or I would use elseif to make the variable updates more predictable.
Best.
回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!