How to calculate between the elements in an array for consecutive indexes.
1 view (last 30 days)
Show older comments
I have a time array(T) and two index arrays.(example)
idx_1 = [32,33,34,35,36,37,38,39,40] % 1 set of consecutive numbers
idx_2 = [32,33,35,36,37,38,40,41,42] % 3 sets of consecutive numebers
What I want to do is to subtract the last vlaue from the first value among the consecutive indexes.
so in the case of idx_1, I want
T(40)-T(32)
and for idx_2,
T(42)-T(40) + T(38)-T(35) + T(33)-T(32)
I have a lot of the T arrays and I can find the index for what I need, but I'm stuck in making the code for this problem.
If anyones can help, thanks in advance :)
0 Comments
Accepted Answer
John D'Errico
on 20 May 2021
Edited: John D'Errico
on 20 May 2021
idx_1 = [32,33,34,35,36,37,38,39,40]; % 1 set of consecutive numbers
idx_2 = [32,33,35,36,37,38,40,41,42]; % 3 sets of consecutive numebers
First, see what happen when you form the diff. If diff > 1, that indicates something special. Do you see that?
diff([-inf,idx_2,inf])
Note that I appended -inf and to inf each end, so that find will trigger for the start and end of each sub-sequence.
loc1 = find(diff([-inf,idx_1,inf])>1)
loc2 = find(diff([-inf,idx_2,inf])>1)
So there is ONE sub-sequence in the first set, and three in the second. How will we use them? It looks like you wish to form a sum, so this will do it:
sum(T(idx1(loc1(2:end) - 1)) - T(idx1(loc1(1:end-1))))
sum(T(idx2(loc2(2:end) - 1)) - T(idx2(loc2(1:end-1))))
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays 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!