Grouping matched data by row and column

1 view (last 30 days)
I have a matrix attached, Rows_col.mat. This gives the Row and column of some other matrix that has matched a condition I have imposed. So for example, 6 has matched with 1, 19 has matched with 7. However there are occasions where there are more matches, for example 9 has matched with 3, but 17 has also matched with 3. In this instance I would like the output to be [9, 17, 3] (the order is not important). I think the output in a cell array would be the most suitable since there is a varying matrix column size for each "match". I hope this is clear, This for example would be the desired output:
[6,1];[9,3,17 (any order would be fine)];[19,7];[15,10,23];[12,11,18];[21,13];[20,14], this would be a 7x1 cell.
Thankyou.
  3 Comments
Guillaume
Guillaume on 23 Mar 2016
In your example you have several rows matching the same column. Could you also have several columns matching the same row, i.e:
6 1
6 2
Or even a mixture of two:
6 1
6 2
5 2
which would give a permutation of [1 2 5 6]?
In your output example of [9 3 17] are you sure you don't care anymore if a number comes from a row or column?
Matlab User
Matlab User on 23 Mar 2016
I'm not sure that my explanation was good enough. I would like, for example you see in my matrix that there is a [9, 3] pair and also a [17, 3]. They both share a common value, 3, so I would like to concatenate the elements, so now [9,3,17] are all in one. When it comes to the order, I meant that it would be fine to have [3 9 17],[9 ,3,17 ],[17,3,9]...ETC, so long as all three (in this case) elements are there.

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 23 Mar 2016
Edited: Guillaume on 23 Mar 2016
I don't think that there is any other way than using loops to solve this. This works:
Rows_col_ = [6 1; 9 3; 17 3; 19 7; 17 9; 15 10; 23 10; 12 11; 18 11; 18 12; 21 13; 20 14; 23 15];
sequences = {};
for row = Rows_col_' %iterate over the rows of Rows_Cols
hascommonvalue = cellfun(@(s) any(ismember(row, s)), sequences); %check if current row has any value common to a stored sequence
if any(hascommonvalue)
%current row has a common value with one or more sequence already stored, group all together
newmatch = unique([sequences{hascommonvalue}, row']); %concatenate all matching sequences and current row
sequences(hascommonvalue) = []; %remove matching sequences since they've been concatenated as a new sequence
sequences{end+1} = newmatch; %and add new sequence
else
%current did not match any previous sequence, add as new
sequences{end+1} = row';
end
end
  1 Comment
Matlab User
Matlab User on 24 Mar 2016
Thankyou, I was trying to avoid loops but this works very well so thanks again.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!