Can you help me ?
2 views (last 30 days)
Show older comments
zainab hp
on 5 Nov 2015
Commented: Walter Roberson
on 7 Nov 2015
Salam: I want to combine two or more row with same first column in the matrix .
from
A = [1 2 3 4;
1 5 6 1;
2 2 3 4;
2 5 6 1;
2 6 7 8;
3 1 2 3;
4 1 2 3
4 5 8 7];
to
A = [1 2 3 4 5 6 1 0 0 0;
2 2 3 4 5 6 1 6 7 8;
3 6 7 8 0 0 0 0 0 0;
4 1 2 3 5 8 7 0 0 0];
2 Comments
Image Analyst
on 5 Nov 2015
Why?
What kind of array do you want? A double with NaN in the "missing" columns on the right, or a cell array with nulls in the missing cells on the right?
Accepted Answer
Walter Roberson
on 6 Nov 2015
Numeric arrays cannot have different number of columns for each row.
2 Comments
Walter Roberson
on 7 Nov 2015
A1 = A(:,1);
[uA1, ~, idx] = unique(A1);
maxidx = max(idx);
maxmerge = max( histc(idx, 1:maxidx) );
Anew = zeros(maxidx, size(A,2)*(maxmerge - 1) + 1);
Anew(:,1) = uA1;
for K = 1 : length(idx)
targetrow = idx(K);
now put A(K,2:end) at the "end" of Anew(targetrow,:)
end
Now to put A(K,2:end) at the "end" of Anew(targetrow,:) is left as an exercise for you.
Note: you did not define the order of the row results when column 1 of A is not in sorted order. I picked an arbitrary order that aesthetically pleased me.
Note: you did not define the order of merging the rows that have the same column 1. I picked an arbitrary order that aesthetically pleased me.
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping 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!