I want to combine two or more row with same first column in the matrix .

2 vues (au cours des 30 derniers jours)
zainab hp
zainab hp le 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];
  1 commentaire
Jan
Jan le 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 ...

Connectez-vous pour commenter.

Réponses (3)

Jan
Jan le 7 Nov 2015
Modifié(e) : Jan le 7 Nov 2015
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
Geoff Hayes le 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
Matt J le 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{:})

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Tags

Aucun tag saisi pour le moment.

Community Treasure Hunt

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

Start Hunting!

Translated by