How to find difference between succesive numbers

14 views (last 30 days)
I have a "2823x1" data sheet, with numbers going from -20 till 20. I want to find all numbers that have a difference of 15 compared with the next 3 numbers.
example:
14*
7
-4*
8
-3*
15*
10
11

Accepted Answer

Cam Salzberger
Cam Salzberger on 13 Nov 2017
I'm not totally sure I understand the question, but this is how I am interpreting it. You have an array of data, and would like to determine which entries, when compared with any of the subsequent three entries, will have an absolute difference in value of 15 or greater.
I will assume that you can get the data into an array in MATLAB using one of the many data import techniques.
If you were just checking the entries against their subsequent value, this would largely be trivial using the diff function:
% For reproducibility
rng default
% Sample data
v = randi([-20 20], 10, 1);
% Get the difference between entries
dv = diff(v);
% Get the applicable entries
whichVals = abs(dv) >= 15;
% Tack on a false on the end because the last entry won't ever be applicable
whichVals = [whichVals ; false];
% Applicable values
v(whichVals)
% Applicable indices (which generally aren't needed)
find(whichVals)
Now, you could probably come up with something fancy using convolution or something similar to deal with all three subsequent values at once. But since you are checking a known and small number of subsequent values, it might be easier to just check each of them individually. You can use some basic indexing to check the second value after the value in question, though you have to check evens and odds separately:
evenIdx = 2:2:numel(v);
oddIdx = 1:2:numel(v);
dvEven = diff(v(evenIdx));
dvOdd = diff(v(oddIdx));
whichVals(evenIdx) = whichVals(evenIdx) | [abs(dvEven) >= 15 ; false];
whichVals(oddIdx) = whichVals(evenIdx) | [abs(dvOdd) >= 15 ; false];
The OR with the previous values of whichVals is done because the value still counts if it were found to have a valid difference with the next index, not the one after that.
You can do something similar for the values separated by three from the entry of interest.
-Cam

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!