필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
zainab hp
zainab hp 2015년 11월 7일
답변: Matt J 2015년 11월 7일
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];

답변 (3개)

Jan
Jan 2015년 11월 7일
편집: Jan 2015년 11월 7일
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 2015년 11월 7일
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 2015년 11월 7일
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{:})

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by