问题描述
这是一个关于在同一个语句多次递增MATLAB阵列的一个值,而无需使用for循环的问题。
This is a question about incrementing one value of a MATLAB array multiple times in the same statement, without having to use a for loop.
设置我的数组:
>> A = [10 20 30];
然后运行:
>> A([1, 1]) = A([1, 1]) + [20 3]
A =
13 20 30
显然,20被忽略。不过,我想它被收录,因此:
Clearly the 20 is ignored. However, i would like it to be included, so that:
>> A = [10 20 30];
>> A([1, 1]) = A([1, 1]) + [20, 3]
会给:
A =
33 20 30
是否有一个功能,允许这种在一个不错的,矢量化的方式进行?
Is there a function to allow this to be done in a nice, vectorised fashion?
(在现实中,分度到阵列将包括多个索引,因此它可能是 [1 1 2 2 1 1 1 1 3 3 3]
等,与数字的数组,递增(即 [20,3]
以上)的长度相同。)
(In reality, the indexing to the array would include multiple indexes, so it could be [1 1 2 2 1 1 1 1 3 3 3]
etc., with an array of numbers to increment by (the [20, 3]
above) of the same length.)
推荐答案
你想做什么,可以使用函数的,像这样:
What you want to do can be done using the function ACCUMARRAY, like so:
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
和本实施例的输出应为:
And the output of this example should be:
A = [33 40 30];
结果
修改如果 A
是一个大阵的价值观,并有短短的增量增加,下面可能比计算效率更高上图:
If A
is a large array of values, and there are just a few increments to add, the following may be more computationally efficient than the above:
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
这篇关于递增一个MATLAB阵列的一个值多次在一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!