Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
zainab hp
zainab hp el 7 de Nov. de 2015
Respondida: Matt J el 7 de Nov. de 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];

Respuestas (3)

Jan
Jan el 7 de Nov. de 2015
Editada: Jan el 7 de Nov. de 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 el 7 de Nov. de 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 el 7 de Nov. de 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{:})

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Community Treasure Hunt

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

Start Hunting!

Translated by