代码之家  ›  专栏  ›  技术社区  ›  Bill Cheatham

在一行中多次增加matlab数组的一个值

  •  2
  • Bill Cheatham  · 技术社区  · 14 年前

    这是一个关于在同一语句中多次增加一个matlab数组值的问题,而不必使用for循环。

    我将数组设置为:

    >> A = [10 20 30];
    

    然后运行:

    >> A([1, 1]) = A([1, 1]) + [20 3]
    
    A =
    
        13    20    30
    

    显然,20个被忽略了。但是,我希望它包括在内,以便:

    >> A = [10 20 30];
    >> A([1, 1]) = A([1, 1]) + [20, 3]
    

    将给予:

    A =
    
        33    20    30
    

    有没有一个函数可以让这个过程以一种漂亮的、矢量化的方式完成?

    (实际上,对数组的索引将包含多个索引,因此可以 [1 1 2 2 1 1 1 1 3 3 3] 等,用一个数字数组递增 [20, 3] 以上)相同长度。)

    2 回复  |  直到 14 年前
        1
  •  11
  •   gnovice    14 年前

    您要做的可以使用函数 ACCUMARRAY ,像这样:

    A = [10 20 30];            %# Starting array
    index = [1 2 2 1];         %# Indices for increments
    increment = [20 10 10 3];  %# Value of increments
    A = accumarray([1:numel(A) index].',[A increment]);  %'# Accumulate starting
                                                          %#   values and increments
    

    这个例子的输出应该是:

    A = [33 40 30];
    


    编辑: 如果 A 是一个大的值数组,并且只需要添加几个增量,下面的计算效率可能比上面的更高:

    B = accumarray(index.',increment);  %'# Accumulate the increments
    nzIndex = (B ~= 0);               %# Find the indices of the non-zero increments
    A(nzIndex) = A(nzIndex)+B(nzIndex);  %# Add the non-zero increments
    
        2
  •  1
  •   Jonas    14 年前

    也许有些事情我不太明白,但你基本上是想在a的第一个元素中加23,对吧?所以你可以写:

    A([1, 1]) = A([1, 1]) + sum([20 3])
    

    另外,如果您有一个索引数组,您可以编写

    indexArray = [1 2 2 3 1 1 2 1];
    toAdd = [20 3];
    A = [10 20 30];
    
    A(indexArray) + sum(toAdd)
    
    ans =
    33    43    43    53    33    33    43    33