假设有一个矩阵
A =
1 3 2 4
4 2 5 8
6 1 4 9
例如,我有一个 Vector 包含该矩阵每一列的“类”
v = [1 , 1 , 2 , 3]
如何将矩阵的列作为列向量求和到一个新矩阵中,每个列向量都对应于它们所在类别的列?在此示例中,A 的第 1 列和第 2 列将添加到新矩阵的第一列,第 2 列到第 3 列到第 2 列,第 4 列到第 3 列。
喜欢
SUM =
4 2 4
6 5 8
7 4 9
这可能没有循环吗?
最佳答案
结合 accumarray
和 bsxfun
功能的完美方案之一 -
%// Since we are to accumulate columns, first step would be to transpose A
At = A.' %//'
%// Create a vector of linear IDs for use with ACCUMARRAY later on
idx = bsxfun(@plus,v(:),[0:size(A,1)-1]*max(v))
%// Use ACCUMARRAY to accumulate rows from At, i.e. columns from A based on the IDs
out = reshape(accumarray(idx(:),At(:)),[],size(A,1)).'
sample 运行-
A =
1 3 2 4 6 0
4 2 5 8 9 2
6 1 4 9 8 9
v =
1 1 2 3 3 2
out =
4 2 10
6 7 17
7 13 17
关于matlab - 如何遍历 matlab 中矩阵的列并将它们分别添加到 matlab 中求和矩阵的特定列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545361/