【问题标题】:MATLAB. How can I sum all the rows of the first column when on the second column the rows have the same value?MATLAB。当第二列的行具有相同的值时,如何对第一列的所有行求和?
【发布时间】:2018-04-25 23:07:28
【问题描述】:

在 MATLAB 上。假设我有一个矩阵 A(i,j)。在这种情况下,i=5 且 j=4。当第二列的行具有相同的值时,我想对第一列的所有行求和。采用如下矩阵:

4000    54571
4000    54571
4000    54572
4000    54573
4000    54574

我想写一个返回的代码:

8000    54571
4000    54572
4000    54573
4000    54574

你对如何做到这一点有想法吗?

非常感谢,

【问题讨论】:

标签: matlab


【解决方案1】:

您可以使用uniqueaccumarray 分两步完成此操作

octave:1> X=[4000    54571
> 4000    54571
> 4000    54572
> 4000    54573
> 4000    54574
> ]
X =

    4000   54571
    4000   54571
    4000   54572
    4000   54573
    4000   54574

octave:2> [keys,~,values] = unique(X(:,2));
octave:3> [accumarray(values,X(:,1)), keys]
ans =

    8000   54571
    4000   54572
    4000   54573
    4000   54574

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2015-07-17
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多