Info
This question is closed. Reopen it to edit or answer.
Help required with deleting rows of a matrix with similar first 2 elements (after summing up the last elements of rows to be deleted)
1 view (last 30 days)
Show older comments
[1069 12059 100200 145
1069 12063 100200 471
1073 1001 100100 213
1073 1001 100101 213
1073 1007 100100 633
1073 1007 100101 633]
This is a portion of the matrix. As you can see that 1073-1001 and 1073-1007 is repeated twice (which is not true for the entire matrix; we might have 3 such pairs for eg: 1073-1008 may occur thrice below this). I want their to be only one row for 1073-1001 and 1073-1007 with the elements in column 4 being 213+213=426 and 633+633=1266, respectively.
So I want the output to be like:
[1069 12059 100200 145
1069 12063 100200 471
1073 1001 100100 426
1073 1007 100100 1266]
The actual matrix has dimensions 10730x4
Having just started using matlab I am facing severe difficulties in solving this problem. Any help will be much appreciated. Thank you.
7 Comments
Image Analyst
on 1 Oct 2013
Just attach the m-file where you create this array. Use the paper clip icon.
Answers (2)
Jan
on 30 Sep 2013
Edited: Jan
on 1 Oct 2013
Do you mean this:
[dummy, Index] = unique(Data(:, 1:2), 'rows');
Result = Data(Index, :);
[EDITED] With adding the corresponding elements from the 4th column:
[dummy, Index] = unique(Data(:, 1:2), 'rows');
S = accumarray(Index(:), Data(:, 4));
Result = cat(2, Data(Index, 1:3), S);
3 Comments
Andrei Bobrov
on 1 Oct 2013
Edited: Andrei Bobrov
on 1 Oct 2013
a = [1069 12059 100200 145
1069 12063 100200 471
1073 1001 100100 213
1073 1001 100101 213
1073 1007 100100 633
1073 1007 100101 633];
[aa,b,c] = unique(a(:,1:2),'first','rows');
out = [aa,a(b,3),accumarray(c,a(:,4))];
another variant only for your example
[~,b2,c2] = unique(a(:,end),'first');
[~,ii] = sort(b2);
out2 = [a(b2(ii),1:end-1), accumarray(ii(c2),a(:,end))];
0 Comments
This question is closed.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!