gpt4 book ai didi

matlab - 按另一个元胞数组的索引对数组求和

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:23 24 4
gpt4 key购买 nike

我有一个数组:

a = [109, 894, 566, 453, 342, 25]

a 的子索引的另一个元胞数组,表示为:

subs = { [1,3,4], [2,5,6], [1,3], [3,4], [2,3,4], [6] };    

我想避免使用 for 循环来通过 MATLAB 计算以下总和:

for i=1:6
sums_a(i) = sum(a(subs{i}));
end

有没有像arrayfun这样快速的方法来实现这个?谢谢。

最佳答案

使用cellfun

sums_a = cellfun( @(sx) sum( a(sx) ), subs );

附言,
最好not to use i and j as variable names in Matlab .

关于matlab - 按另一个元胞数组的索引对数组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16757395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com