How to calculate differences in matrix

53 views (last 30 days)
I have matrix A as follows:
A = [
1 245
1 370
1 1555
1 1620
2 255
2 295
2 335
2 1375
2 1415
2 1575
2 1615
2 1655
3 250
3 415
3 520
3 565
3 1405
];
I want to create a new third column where it represent the difference between two successive arrays of the second column of matrix A. The process should be restarted whenever the unique ID (first column) changed. Also, in calculation of last array since ID is changing then the value should be calculated from absolute value of difference between last and first arrays.
out = [
1 245 125
1 370 1185
1 1555 65
1 1620 1375
2 255 40
2 295 40
2 335 1040
2 1375 40
2 1415 160
2 1575 40
2 1615 40
2 1655 1400
3 250 165
3 415 105
3 520 45
3 565 840
3 1405 1155
];
% abs(1620-245) = 1375

Accepted Answer

the cyclist
the cyclist on 24 May 2017
Edited: the cyclist on 25 May 2017
I think this does what you intend
A = [
1 245
1 370
1 1555
1 1620
2 255
2 295
2 335
2 1375
2 1415
2 1575
2 1615
2 1655
3 250
3 415
3 520
3 565
3 1405
];
out = [[A, [diff(A(:,2)); 0]]; [max(A(:,1))+1 0 0]];
indexToOutAbsVal = find(diff(out(:,1))~=0);
out(indexToOutAbsVal,3) = abs(A(indexToOutAbsVal,2) - A([1; indexToOutAbsVal(1:end-1)+1],2)); out(end,:) = [];
  2 Comments
Tiffan
Tiffan on 24 May 2017
Edited: Tiffan on 24 May 2017
@the cyclist, I realized that your code is correct just for first ID (1). The same way for first ID that 1375 = 1620 - 245, for other IDs the last diff should be calculated:
$ e.g. for ID 2: 1655 - 255 = 1400
% e.g. for ID 3: 1405 - 250 = 1155
Result should be like:
1 245 125
1 370 1185
1 1555 65
1 1620 1375
2 255 40
2 295 40
2 335 1040
2 1375 40
2 1415 160
2 1575 40
2 1615 40
2 1655 1400
3 250 165
3 415 105
3 520 45
3 565 840
3 1405 1155
Can you please correct your code?
the cyclist
the cyclist on 25 May 2017
Edited: the cyclist on 25 May 2017
Sorry, I got the indexing wrong. I edited one line in my answer, and it works now.

Sign in to comment.

More Answers (1)

Akira Agata
Akira Agata on 25 May 2017
Another strait forward way to calculate this would be as follows:
A = [
1 245
1 370
1 1555
1 1620
2 255
2 295
2 335
2 1375
2 1415
2 1575
2 1615
2 1655
3 250
3 415
3 520
3 565
3 1405
];
out = zeros(size(A,1),1);
numGroup = max(A(:,1));
for kk = 1:numGroup
idx = A(:,1) == kk;
a = A(idx,2);
out(idx) = [a(2:end) - a(1:end-1); a(end) - a(1)];
end
out = [A, out];

Categories

Find more on Loops and Conditional Statements 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!