How do I create new rows from numbers repeating themselves in two or more rows of a matrix?

1 view (last 30 days)
Take for example matrix a:
a=[1 2 3 4; 5 8 10 1; 2 3 11 12].
Numbers recurring in different rows should create a new row and be emitted from the row they were in before, giving us the matrix:
a=[1 0 0; 2 3 0; 4 0 0; 5 8 10; 11 12 0]
  1 Comment
Walter Roberson
Walter Roberson on 29 Jun 2015
4 does not occur in any other row, so why is it not retained in the row with the 1?
Your duplicates, the 2 and the 3 in this example, do they always occur in pairs, or could they be single?
What should happen for numbers that have multiple duplicates?

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 29 Jun 2015
This is not very easy, so why do you want to do that?
The following may do what you want:
a = num2cell(a, 2); %convert into a cell array of rows
height = numel(a);
result ={};
for row = 1:height;
for otherrow = row+1:height;
if isempty(a{row})
break;
end
[isfound, where] = ismember(a{row}, a{otherrow});
if any(isfound)
result = [result; a{row}(isfound)]; %#ok<AGROW>
a{row}(isfound) = []; %prevent extracted elements to be reprocessed
a{otherrow}(where(isfound)) = []; %remove duplicate
end
end
if ~isempty(a{row})
result = [result; a{row}]; %#ok<AGROW> append non-duplicate
end
end
Note that it puts non-recurring numbers after any recurring numbers in the same row.
  2 Comments
Guillaume
Guillaume on 29 Jun 2015
You need to run it again on your result in order to receive the desired matrix
I assume it's in response to Walter's question: What should happen for numbers that have multiple duplicates?.
My code above ignores the issue in that it only removes a number and its first duplicate from further processing. A third duplicate will thus be considered a unique value again.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!