How to calculate differences in matrix
53 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
the cyclist
2017 年 5 月 24 日
編集済み: the cyclist
2017 年 5 月 25 日
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 件のコメント
the cyclist
2017 年 5 月 25 日
編集済み: the cyclist
2017 年 5 月 25 日
Sorry, I got the indexing wrong. I edited one line in my answer, and it works now.
その他の回答 (1 件)
Akira Agata
2017 年 5 月 25 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!