How to find the rows with the same values, and to merge those?

13 views (last 30 days)
I would want to know a way to find the rows having the same value in the first column (id), and combine those rows together.
Suppose I have the matrix A;
A = [1 2 3 4;
1 5 6 0;
2 2 3 4;
2 5 6 0;
2 6 7 8;
3 1 2 3;
4 1 2 3]
What I want to do is to find the rows with same ids (1st column), and merge their features (other columns). In this case, I need the following matrix.
A = [1 2 3 4 5 6 0 0;
2 2 3 4 5 6 7 8;
3 1 2 3 0 0 0 0;
4 1 2 3 0 0 0 0];

Accepted Answer

Image Analyst
Image Analyst on 27 Aug 2014
Sounds like a homework assignment (tag it as homework if that's true), so how about I just get it started for you:
A = [1 2 3 4;
1 5 6 0;
2 2 3 4;
2 5 6 0;
2 6 7 8;
3 1 2 3;
4 1 2 3]
% Find unique numbers in the first column.
uniqueCol1 = unique(A(:,1))
% Find out how many times each number occurs.
counts = hist(A(:,1), uniqueCol1)
% Find out how big our output matrix needs to be, and create it.
rows = length(uniqueCol1);
columns = 3 * max(counts);
outputA = zeros(rows, columns, 'int32');
% Assign first column
outputA(:,1) = uniqueCol1
You can finish it.
  2 Comments
Sam
Sam on 27 Aug 2014
Edited: Sam on 27 Aug 2014
Actually, it is not a homework. I have C background, and just try to learn how to do such things in MATLAB without using for loops .
Thanks
Image Analyst
Image Analyst on 27 Aug 2014
OK. Here's the full script.
workspace
A = [1 2 3 4;
1 5 6 0;
2 2 3 4;
2 5 6 0;
2 6 7 8;
3 1 2 3;
4 1 2 3]
% Find unique numbers in the first column.
uniqueCol1 = unique(A(:,1))
% Find out how many times each number occurs.
counts = hist(A(:,1), uniqueCol1)
% Find out how big our output matrix needs to be, and create it.
rows = length(uniqueCol1);
columns = 3 * max(counts);
outputA = zeros(rows, columns, 'int32');
% Assign first column
outputA(:,1) = uniqueCol1
cols234 = A(:,2:end)
% Fill up output rows.
for row = 1 : length(uniqueCol1)
% Get a unique number from column 1 of A
thisNumber = uniqueCol1(row);
rowsWithThisNumber = A(:,1) == thisNumber; % Logical vector.
theseRows = cols234(rowsWithThisNumber,:)'; % Row vector
% Assign this row vector to the row from col 2 onwards.
outputA(row,2:numel(theseRows)+1) = theseRows(:);
end
% Print to command window.
outputA
Someone may come along with a shorter cryptic one-liner but I think this is easy to understand. If it meets your needs, mark the Answer as accepted.

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!