MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   一行中多次增加MATLAB数组的一个值 (https://www.labfans.com/bbs/showthread.php?t=24010)

poster 2019-12-10 20:48

一行中多次增加MATLAB数组的一个值
 
这是一个关于在同一条语句中多次增加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] )的相同长度。)



[B]回答:[/B]

您可以使用功能[URL="http://www.mathworks.com/help/techdoc/ref/accumarray.html"]ACCUMARRAY[/URL]完成您想做的事情,如下所示:

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];
[B]编辑:[/B]如果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

[url=https://stackoverflow.com/questions/3955109]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 01:11

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.