I want to combine two or more row with same first column in the matrix .
Show older comments
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];
1 Comment
Jan
on 7 Nov 2015
The 3rd line of the output should be:
3 1 2 3 0 0 0 ..
instead of
3 6 7 8 0 0 0 ...
Answers (3)
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];
key = A(:, 1);
v = unique(key);
B(:, 1) = v;
for index = 1:length(v)
data = A(key == v(index), 2:end).';
B(index, 2:numel(data) + 1) = reshape(data, 1, []);
end
Geoff Hayes
on 7 Nov 2015
zainab - there are several ways to solve this problem. You can use unique to get the unique integers in the first column of A as
uniqueColumn1Values = unique(A(:,1));
then you can iterate over each of these unique values and find all of those rows which start with that unique value. First, size your output matrix B using mode to determine what is the maximum number of columns for B (we use mode to return the most frequent value in the first column of A and use the frequency f to determine that maximum)
[m,f] = mode(A(:,1));
B = zeros(length(uniqueColumn1Values),f*(size(A,2)-1)+1);
B(:,1) = uniqueColumn1Values;
for k=1:length(uniqueColumn1Values)
idcs = find(A(:,1)==uniqueColumn1Values(k)); % get indices of matching rows
temp = A(idcs,2:end); % create temp matrix
B(k,2:numel(temp)+1) = reshape(temp',1,numel(temp)); % reshape matrix to array
end
The above sets B as
B =
1 2 3 4 5 6 1 0 0 0
2 2 3 4 5 6 1 6 7 8
3 1 2 3 0 0 0 0 0 0
4 1 2 3 5 8 7 0 0 0
There is a lot going on in the above code so you may want to step through it with the debugger to get a better idea as to what is going on.
I do suspect that there are easier ways to get the above too! :)
Matt J
on 7 Nov 2015
S=accumarray(A(:,1),(1:size(A,1)).',[],@(r) {reshape(A(r,2:end),1,[])});
N=max(cellfun('length',S));
S=cellfun(@(c)[c,zeros(1,N-length(c))],S,'uni',0);
Anew=vertcat(S{:})
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!