Reputation: 309
I have an input matrix as below
all = [12 16;12 13;8 14;14 19;3 6;8 6;13 25;25 14;7 2];
I need the following output
output = [12 16;8 14;3 6;13 25;7 2];
The explanation for the output is as follows.
First row of input i.e. 12 16
is the first row in output as both the numbers have never been repeated before in the output matrix (obviously).
Second row of input i.e 12 13
is not needed as the number 12
is present in first row of output i.e repeated
Third row of input i.e 8 14
is second row of output as both the numbers have never been repeated before in the output matrix.
Fourth row of input i.e 14 19
is not needed as the number 14
is present in output i.e repeated
On similar lines
3 6
needed as both are not repeated,
8 6
not needed as both 8
and 6
are repeated,
13 25
needed as both are not repeated
25 14
not needed as both are repeated
7 2
needed as both are not repeated
I am not able to get any ideas to start. Any help will be appreciated.
Thanks!
Upvotes: 2
Views: 152
Reputation: 112659
This assumes that if a row contains two equal values they count as repeated and thus the row should be removed.
Don't use all
as a variable name, because that shadows a function:
A = [12 16;12 13;8 14;14 19;3 6;8 6;13 25;25 14;7 2]; % input matrix
[~, u] = unique(A.', 'first'); % unique values of linearized transposed A.
% In recent Matlab versions you an remove 'first '
M = false(flip(size(A))); % initiallize mask of values to be kept
M(u) = true; % fill values
output = A(all(M,1),:); % keep rows that only have non-repeated values
This gives
output =
12 16
8 14
3 6
7 2
Upvotes: 1
Reputation: 5822
One Liner Solution
res = all(arrayfun(@(ii) isempty(intersect(all(1:ii-1,:),all(ii,:))),1:size(all,1)),:);
Result
res =
12 16
8 14
3 6
7 2
Explanation
let's divide the one-liner into a more detailed and documented chunk of code:
%defines a function which validates for each index wheter the row is
%completely unique are not.
uniqueRowIndicator = @(ii) isempty(intersect(all(1:ii-1,:),all(ii,:)));
%finds all the unique row in the matrix
inds = arrayfun(uniqueRowIndicator,1:size(all,1));
%extracts the result from the returned indices
res = all(inds,:);
Upvotes: 2