# Matrix problem for same values of column

1 view (last 30 days)
Anu Sharma on 2 Sep 2019
Answered: Andrei Bobrov on 2 Sep 2019
A=[29.78 5 8
24.97 8 11
22.98 4 12
21.05 12 13
24.78 1 16
25.53 26 29
21.43 2 32
29.94 11 33
29.57 15 35
28.43 17 36
11.49 23 37
13.69 37 38
26.97 28 39
16.25 25 40
27.36 36 41
4.24 18 42
19.39 39 44
29.93 16 45
25.83 30 46
26.09 40 47
27.58 24 48
28.61 41 49
29.41 48 50]
and i want
output =[22.98 4 12
25.53 26 29
21.43 2 32
29.94 11 33
29.57 15 35
28.43 17 36
13.69 37 38
26.97 28 39
4.24 18 42
29.93 16 45
25.83 30 46
26.09 40 47
28.61 41 49
29.41 48 50 ]
No value in column 2, 3 get repeated and in case of repeated value in any of the column(2,3) the higest value of column 1 is as the output.
For example, in row 1, 2 and 8. column (2,3) have values as
[ 5 8
8 11
11 33]
Among these 3 rows row 8, ie. [29.94 11 33] have the highest value so only this row will be the output. all other row like [29.78 5 8] and [24.97 8 11]will be elimanted.
simillarly,
for row 3 = [22.98 4 12]
And 4 = [21.05 12 13]
row 3= [22.98 4 12]
will be output and row 4 will get eliminated.

#### 1 Comment

Stephen Cobeldick on 2 Sep 2019
Is the row
28.43 17 36
correct in your example output array? Following your explanation, these rows are one group:
28.43 17 36
...
27.36 36 41
...
28.61 41 49
of which the last row has the highest values in the first column (and the last row is in your output array). But why do you keep the first row as well?

Stephen Cobeldick on 2 Sep 2019
Edited: Stephen Cobeldick on 2 Sep 2019
N = size(A,1);
X = ones(N,1); % group numbers
Z = true(N,1); % logical index
V = 1; % group number
for k = 2:N % for each row...
Y = A(k,2)==A(1:k-1,3); % check if any matching rows.
if any(Y)
X(k) = X(Y); % copy group number (assumed scalar).
W = X(k)==X(1:k-1); % logical index of that group.
if all(A(k,1)>A(W,1))
Z(W) = false; % current val > prev vals.
else
Z(k) = false; % prev val > current val.
end
else % no matching rows:
V = V+1; % increment group number.
X(k) = V;
end
end
B = A(Z,:) % output matrix
Giving:
B =
22.98 4 12
25.53 26 29
21.43 2 32
29.94 11 33
29.57 15 35
13.69 37 38
26.97 28 39
4.24 18 42
29.93 16 45
25.83 30 46
26.09 40 47
28.61 41 49
29.41 48 50

Anu Sharma on 2 Sep 2019
please tell me, In which variable ,output matrix is storing.
Stephen Cobeldick on 2 Sep 2019
"In which variable ,output matrix is storing. "
B
Anu Sharma on 2 Sep 2019
Thankyou so much..

### More Answers (1)

Andrei Bobrov on 2 Sep 2019
[m,n] = size(A);
B = [(1:m)',A(:,2:3)];
k = B(1,2:3);
ii = 1;
C{1} = [];
while ~isempty(B)
i0 = ismember(B(:,2:3),k);
lo = any(i0,2);
if any(lo)
C{ii} = [C{ii};[repmat(ii,nnz(lo),1),B(lo,1)]];
k = B(xor(i0(:,1),i0(:,2)),2:3);
B = B(~lo,:);
else
ii = ii + 1;
k = B(1,2:3);
C{ii} = [];
end
end
iii = cat(1,C{:});
T = array2table(A);
T = T(iii(:,2),:);
T.g = iii(:,1);
T = sortrows(T,{'g','A1'},{'ascend','descend'});
T = rowfun(@(x,y,z)[x(1),y(1),z(1)],T,'GroupingVariables','g');