合并两个矩阵及其在Matlab属性 [英] merge two matrix and its attributes in matlab

查看:381
本文介绍了合并两个矩阵及其在Matlab属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于两个矩阵A和B,我想对行的方式相结合,第一行中我没有重复的值,并在第二个值,列A和B上有相同的行值获得新的矩阵相加。即

I've two matrix a and b and I'd like to combine the rows in a way that in the first row I got no duplicate value and in the second value, columns in a & b which have the same row value get added together in new matrix. i.e.

a =
 1     2     3
 8     2     5

b =
 1     2     5     7
 2     4     6     1

期望outputc =

Desired outputc =

 1     2     3     5     7
10     6     5     6     1

任何帮助,欢迎,欢迎。

Any help is welcomed,please.

推荐答案

您想添加对应相同的第一行值第二排值。这是一个典型的使用 唯一 accumarray

For two-row matrices

You want to add second-row values corresponding to the same first-row value. This is a typical use of unique and accumarray:

[ii, ~, kk] = unique([a(1,:) b(1,:)]);
result = [ ii; accumarray(kk(:), [a(2,:) b(2,:)].').'];

一般情况下

如果你需要列任意数量(基于第一排值)积累列,可以使用的 稀疏 如下:

[ii, ~, kk] = unique([a(1,:) b(1,:)]);
r = repmat((1:size(a,1)-1).', 1, numel(kk));
c = repmat(kk.', size(a,1)-1, 1);
result = [ii; full(sparse(r,c,[a(2:end,:) b(2:end,:)]))];

这篇关于合并两个矩阵及其在Matlab属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆