MATLAB Answers

remove repeated rows to produce two new matrices

1 view (last 30 days)
JL
JL on 12 Sep 2019
Edited: Stephen on 12 Sep 2019
Hi everyone, I have 2 matrices, A and B. As you can see, everyrow in A is for a particular row in B. What I want to to do is for a repetitive, I want to remove them and take the highest value in A. For example, 3 to 10 appears twice (3 4 5 7 8 10 & 3 4 5 6 9 8 10 with corresponding A values of 0.213157025 and 0.207067988 respectively). From this two, I would take 0.213157025 because its higher. I then produce C and D accordingly by producing C in terms of putting the first and last number in each row with their corresponding A values in D.
a = [0.359883241
0.277815278
0.247562838
0.26249033
0.226989582
0.213157025
0.207067988
0.204762201
];
b =[3 4 0 0 0 0 0
3 4 5 0 0 0 0
3 4 5 7 6 0 0
3 4 5 7 0 0 0
3 4 5 7 8 0 0
3 4 5 7 8 10 0
3 4 5 6 9 8 10
3 4 5 7 8 10 11
];
I would like to produce C and D
C =[3 4
3 5
3 6
3 7
3 8
3 10
3 11]
D = [0.359883241
0.277815278
0.247562838
0.26249033
0.226989582
0.213157025
0.204762201
];

Accepted Answer

Adam Danz
Adam Danz on 12 Sep 2019
% Convert b to [first,last] non-zero per row
b2 = splitapply(@(x)x([find(x~=0,1,'first'),find(x~=0,1,'last')]),b,(1:size(b,1)).');
% Get unique rows of b2
[C, Cidx] = unique(b2,'rows');
% Get the corresponding 'a' values
D = a(Cidx);

More Answers (1)

Stephen
Stephen on 12 Sep 2019
Edited: Stephen on 12 Sep 2019
An old-fashioned way:
a = [0.359883241;0.277815278;0.247562838;0.26249033;0.226989582;0.213157025;0.207067988;0.204762201]
b = [3,4,0,0,0,0,0;3,4,5,0,0,0,0;3,4,5,7,6,0,0;3,4,5,7,0,0,0;3,4,5,7,8,0,0;3,4,5,7,8,10,0;3,4,5,6,9,8,10;3,4,5,7,8,10,11]
% Indices of last non-zero:
tmp = b.';
tmp(end+1,:) = 0;
idx = 1==diff(cumprod(tmp,1)==0);
idx(end+1,:) = false;
%
[T,X] = sortrows([b(:,1),tmp(idx),a]);
[C,Y] = unique(T(:,1:2),'rows','last');
D = a(X(Y));
Giving:
>> C
C =
3 4
3 5
3 6
3 7
3 8
3 10
3 11
>> D
D =
0.35988
0.27782
0.24756
0.26249
0.22699
0.21316
0.20476

Community Treasure Hunt

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

Start Hunting!

Translated by