How to create a vector based on previous value of same vector
이전 댓글 표시
I am trying to create a vector where the value of a particular element depends on the value of a previous element. Specifically, I have a vector of torque values, and when the values are above a threshold, I want my new vector to hold true until the torque level drops below the threshold plus some hysteresis.
An example. In this case Active = 1 when Torque > 6, but Active doesn't = 0 again until Torque < 4.
Torque = [0 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 0];
Active = [0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0];
Is there a way to do this with vector operations? I am interested in speed, so while a for loop will work easily, I want it to be as fast as possible.
Thanks.
댓글 수: 3
Russell Senior
2019년 6월 5일
dpb
2019년 6월 5일
Use the loop and go on--then profile the end result to see if this ends up being the bottleneck. I'm guessing you'll find your actual choke points will be something else.
Don't try to micro-optimize; wait until you know where the real issues are--until then, write most "dead ahead" code you can until it is shown to somehow be inadequate.
Russell Senior
2019년 6월 10일
답변 (1개)
I suspect overall performance will not be significantly improved as removing a small fraction of a total run time entirely will still be only a small fraction of the total.
But to the original question alone...
On=6; Off=4; % or whatever limits are
S=[false sign(diff(Torque))]; % accel/decel?
Active=(Torque>=On & S>=0) | (Torque>=Off & S<0);
will work for patterns such as the example--whether will be sufficient in general for real data is another Q?
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!