Subtracting elements within a table

11 views (last 30 days)
I have a table:
1 23
2 24
3 21
4 34
1 89
2 23.2
3 34.8
4 -23.1
and it continues with the first column always being in the sequence 1-2-3-4.
I need to subract the first element next to 1 from the second element next to 1, so: 89-23. Then all elemets represented by the number 2 in the 1st column, so: 23.2-24. etc.
The outcome should be the following vector: [66 -0.8 13.8 -57.1].

Accepted Answer

Arif Hoq
Arif Hoq on 13 Feb 2022
A=[1 23
2 24
3 21
4 34
1 89
2 23.2
3 34.8
4 -23.1];
My_Table= table(A(:,1),A(:,2))
My_Table = 8×2 table
Var1 Var2 ____ _____ 1 23 2 24 3 21 4 34 1 89 2 23.2 3 34.8 4 -23.1
B=table2array(My_Table(:,2));
ind1 = 1:4;
ind2 = ind1 + 4;
output=B(ind2)-B(ind1)
output = 4×1
66.0000 -0.8000 13.8000 -57.1000
  1 Comment
Lu Da Silva
Lu Da Silva on 15 Feb 2022
worked perfectly, thanks!
Since the table is actually longer, I made a small adjustment:
ind1 = 1:length(B)-4;

Sign in to comment.

More Answers (0)

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!