这是一个关于在同一语句中多次递增MATLAB数组的一个值的问题,而无需使用循环。

我将数组设置为:

>> 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] 上面)长度相同。)

有帮助吗?

解决方案

您想使用该功能可以做什么 累积, ,像这样:

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

其他提示

也许有些东西我不完全到达这里,但是您基本上是在尝试将23添加到A的第一个元素中,对吗?因此,您可以写:

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top