How to calculate between the elements in an array for consecutive indexes.

2 次查看(过去 30 天)
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 :)

采纳的回答

John D'Errico
John D'Errico 2021-5-20
编辑:John D'Errico 2021-5-20
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])
ans = 1×10
Inf 1 2 1 1 1 2 1 1 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)
loc1 = 1×2
1 10
loc2 = find(diff([-inf,idx_2,inf])>1)
loc2 = 1×4
1 3 7 10
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))))

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by