poster
2019-12-10, 20:48
这是一个关于在同一条语句中多次增加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] )的相同长度。)
回答:
您可以使用功能ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/accumarray.html)完成您想做的事情,如下所示:
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
更多&回答... (https://stackoverflow.com/questions/3955109)
我将数组设置为:
>> 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] )的相同长度。)
回答:
您可以使用功能ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/accumarray.html)完成您想做的事情,如下所示:
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
更多&回答... (https://stackoverflow.com/questions/3955109)