I want to combine two or more row with same first column in the matrix .
조회 수: 3 (최근 30일)
이전 댓글 표시
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
답변 (3개)
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! :)
댓글 수: 0
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{:})
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!