Checking Previous Value in an Array.

Hey All,
Currently I need to find all values in an array that are over a defined value, if the last 6 preceding values are under 0.
At the moment finding values over the defined value is no problem but I can't figure out how to check for the preceding value. This is what I have right now;
acceleration_z_output = file.data( : , 2 );
acceleration_limit = (5)
Z_Check = acceleration_z_output(acceleration_z_output > acceleration_limit);
I Need something like this;
acceleration_z_output = file.data( : , 2 );
acceleration_limit = (5)
Z_Check = acceleration_z_output(acceleration_z_output > acceleration_limit && last_6_values of acceleration_z_output < 0);
Any Idea How to do this? Cheers

 Accepted Answer

  • Step 1: build a matrix with 6 rows, where each row is your vector shifted one value to the left. Use a loop for that, or toeplitz:
precvals = triu(toeplitz(acceleration_z_output(1:6), acceleration_z_output));
  • Step 2: Use all on the matrix to check that all 6 rows are negative and combine with your original check
Z_check = all(precval(:, 6:end-1) < 0) & acceleration_z_output(7:end) > acceleration_limit;
Obviously, the check is meaningless for the first 6 values.

3 Comments

Thanks for the reply this is almost perfect.
using this example vector and your code like so
acceleration_z_output = [-1 -1 -1 -1 -1 -1 6 -2 -2 -2 -2 -2 -2 8];
precval = triu(toeplitz(acceleration_z_output(1:6),acceleration_z_output));
acceleration_limit = (5);
Z_check = acceleration_z_output(all(precval(:, 6:end-1) < 0) & acceleration_z_output(7:end) > acceleration_limit);
I'm getting an output of the bellow 0 (-1, -2) values, I need the output of the values over the acceleration limit (6, 8). I've tried changing the value in the acceleration_z_output(7:end) part of the code yet this gives me a "matrix dimensions must agree" warning.
Any Ideas?
Sorry, it's a bug in the last line of my code. The logical array only applies to element 7 and up of acceleration_z_output, yet I applied it from the first element. Prepending the logical array by 6 false solves the issue:
Z_check = acceleration_z_output([false(1, 6), all(precval(:, 6:end-1) < 0) & acceleration_z_output(7:end) > acceleration_limit])
perfect. I can finally process all my files with this cheers.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!