How to calculate differences in matrix
53 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
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.
More Answers (1)
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];
0 Comments
See Also
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!