How to calculate differences in matrix

53 ビュー (過去 30 日間)
Tiffan
Tiffan 2017 年 5 月 24 日
編集済み: the cyclist 2017 年 5 月 25 日
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

採用された回答

the cyclist
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 件のコメント
Tiffan
Tiffan 2017 年 5 月 24 日
編集済み: Tiffan 2017 年 5 月 24 日
@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 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
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];

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by