How to calculate differences in matrix

조회 수: 6 (최근 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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by