merge two matrices together
조회 수: 4 (최근 30일)
이전 댓글 표시
I have two matrices as follows
-----------------------------------------
40 40 40 40
41 41 41 41
42 42 42 42
43 44 43 44
43 45 44 44
44 48 45 49
45 50 49 51
50 51 51 52
51 52 52 53
52 53 53 54
------------------------------------------
1282 1687 2501 1466
870 929 644 1141
345 103 736 133
765 7484 1434 3267
2796 461 7021 2143
4689 212 363 241
549 320 343 218
219 761 415 249
187 316 684 868
85 309 271 395
----------------------------------------
Each column and row of the first matrix corresponds to the second matrix
I would like to generate a matrix as follows
40 1282 1687 2501 1466
41 870 929 644 1141
42 345 103 736 133
43 2796+765 0 1434 0
44 4689 7484 7021 3267+2143
45 549 461 363 0
46 0 0 0 0
47 0 0 0 0
48 0 212 0 0
49 0 0 343 241
50 219 320 0 0
51 189 761 415 218
52 85 316 684 249
53 0 309 271 868
54 0 0 0 395
As it can be seen , the first matrix was merged and one column which present all the data of the first matrix is appeared. each row and column of the second matrix corresponds to the first matrix and those that had similar values are sum and those values that do not exist a zero will be replaced.
댓글 수: 0
채택된 답변
Roger Stafford
2013년 5월 22일
If M1 and M2 are your two arrays (of like size), get your desired result in array M3:
[m,n] = size(M1);
[u,~,p] = unique(M1(:));
q = reshape(repmat(1:n,m,1),[],1);
M3 = [u,accumarray([p,q],M2(:),[size(u,1),n])];
댓글 수: 0
추가 답변 (3개)
José-Luis
2013년 5월 21일
ii = [40 40 40 40
41 41 41 41
42 42 42 42
43 44 43 44
43 45 44 44
44 48 45 49
45 50 49 51
50 51 51 52
51 52 52 53
52 53 53 54];
d = [1282 1687 2501 1466
870 929 644 1141
345 103 736 133
765 7484 1434 3267
2796 461 7021 2143
4689 212 363 241
549 320 343 218
219 761 415 249
187 316 684 868
85 309 271 395];
left_side = (min(ii):max(ii))';
mySum = @(idx) sum(d.*(ii==idx),1);
your_result = [left_side cell2mat(arrayfun(@(x) mySum(x),left_side, 'uniformoutput', false))];
Iain
2013년 5월 21일
You ought to be able to mod this to give you exactly what you want - I've made some assumptions that are probably not true.
for i = 1:Rows
New(i,1) = i;
for j = 1:Columns
New(i,1+j) = sum(Old(Indices(i,j),j));
end
end
댓글 수: 7
Andrei Bobrov
2013년 5월 21일
편집: Andrei Bobrov
2013년 5월 21일
ii = [40 40 40 40
41 41 41 41
42 42 42 42
43 44 43 44
43 45 44 44
44 48 45 49
45 50 49 51
50 51 51 52
51 52 52 53
52 53 53 54];
d = [1282 1687 2501 1466
870 929 644 1141
345 103 736 133
765 7484 1434 3267
2796 461 7021 2143
4689 212 363 241
549 320 343 218
219 761 415 249
187 316 684 868
85 309 271 395];
a = min(ii(:)):max(ii(:));
[l1, l2] = ismember(ii,a);
i1 = [l2(l1) kron((1:size(ii,2))',ones(size(ii,1),1))];
out = [a(:), accumarray(i1,d(:))]
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!