MATLAB Answers


How to create a vector based on previous value of same vector

Russell Senior さんによって質問されました 2019 年 6 月 5 日
最新アクティビティ dpb
さんによって 編集されました 2019 年 6 月 11 日
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.

  3 件のコメント

Russell Senior 2019 年 6 月 5 日
I had a little bit of a brainstorm and found a solution using fillmissing, although it is slower. Basically, you create two vectors, A = 1 when Torque>6, and B = 1 When Torque > 4. The final vector is initialized with NaN, and wherever A = B, set final vector is the same value, but will remain NaN anywhere else. use fillmissing with 'previous' method and it works fine. But is slow.
In my application, the For loop is 0.004 seconds, but the fill missing is 0.074s. This function will be run 100,000's of times doing some optimization, so that's why it needs to be as fast as possible.
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 日
I appreciate your response. However, my code was already finished, and I'm trying to optimize it as much as possible. My function itself takes about 54ms after changing as much as I can to vector functions.
The slowest part of my function is a call to the interpn function, which has proven difficult to improve.
The last low hanging fruit would be an answer to my original question. If that, too, proves difficult / impossible to improve, then I will consider 54ms as good as it gets.

サインイン to comment.





1 件の回答

回答者: dpb
2019 年 6 月 10 日
編集済み: dpb
2019 年 6 月 11 日

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?

  0 件のコメント

サインイン to comment.

Translated by