How to compare with the elements before and after

2 次查看(过去 30 天)
I want know the way to comapre with before element and after element.
Please someone tell me.
I want to comapare V_Ball(index) and V_Ball(index+1).
If V_Ball(index) > V_Ball(index+1) , I wanna break simulation. How should I do?
L1 = 1;
L2 = 1;
M1 = 1;
M2 = 1;
T = 0.01;
Theta1 = -3.14;
Theta2 = 1.57;
V1 = 0;
V2 = 0;
DPendulum = classDoublePendulum(L1,L2,M1,M2,Theta1,Theta2,V1,V2,T);
for i = 1:200
Trq1 = -10;
Trq2 = -10;
DPendulum.pstep(Trq1,Trq2);
V = DPendulum.AngleVelocity2;
Angle = cos(DPendulum.Theta2);
V_Ball(i) = V*Angle;
for index = 1 : length(V_Ball)
if abs(V_Ball(index)) - abs(V_Ball(index+1:end)) > 0% compare elements before after
disp(true);
else
disp(false);
end
end
end

回答(1 个)

Davide Masiello
Davide Masiello 2022-2-5
编辑:Davide Masiello 2022-2-5
Your condtional statement says
if abs(V_Ball(index)) - abs(V_Ball(index+1:end)) > 0
which is wrong, beacuse when index=length.V_Ball than index+1 is larger than the size of V_Ball.
Plus, your are checking your statement over the whole array V_Ball at each iteration of the outer loop, while I think you just need to do that for the last two elements.
Another issue is that you are using the absolute value in the conditional statement, which makes it a bit ambiguous because you are not actually checking that V_Ball(index) > V_Ball(index+1) .
Now, I am not sure I correctly understand your problem, but I think this might be a solution
for i = 1:200
Trq1 = -10;
Trq2 = -10;
DPendulum.pstep(Trq1,Trq2);
V = DPendulum.AngleVelocity2;
Angle = cos(DPendulum.Theta2);
V_Ball(i) = V*Angle;
if i = 1
elseif V_Ball(i-1) > V_Ball(i)
disp(true);
break
else
disp(false);
end
end

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by