我有一个大矩阵M(nxm).我将把存储在vector中的索引指定的一些元素作为单元格元素进行求和.有许多索引组,因此单元格有多个元素.例如
M = rand(2103, 2030);
index{1} = [1 3 2 4 53 5 23 3];
index{2} = [2 3 1 3 23 10234 2032];
% ...
index{2032} = ...;
Run Code Online (Sandbox Code Playgroud)
我将总结索引{1}处的所有元素,总结索引{2}处的所有元素...,现在我正在使用循环
sums = zeros(1, 2032);
for n=1:2032
sums(n) = sum(M(index{n}));
end
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何方法可以使用单行命令而不是循环来执行此操作.使用循环非常慢.
可能是经典的用法 cellfun
sums = cellfun(@(idx) sum(M(idx)), index);
Run Code Online (Sandbox Code Playgroud)
编辑:这是一个大案例的基准测试,表明这种方法比for循环略慢,但比Eitan T的方法快
M = rand(2103, 2030);
index = cell(1, 2032);
index{1} = [1 3 2 4 53 5 23 3];
index{2} = [2 3 1 3 23 10234 2032];
for n=3:2032
index{n} = randi(numel(M), 1, randi(10000));
end
N = 1e1;
sums = zeros(1, 2032);
tic
for kk = 1:N
for n=1:2032
sums(n) = sum(M(index{n}));
end
end
toc
tic
for kk = 1:N
sums = cellfun(@(idx) sum(M(idx)), index);
end
toc
tic
for kk = 1:N
sums = cumsum(M([index{:}]));
sums = diff([0, sums(cumsum(cellfun('length', index)))]);
end
toc
Run Code Online (Sandbox Code Playgroud)
结果是
Elapsed time is 2.072292 seconds.
Elapsed time is 2.139882 seconds.
Elapsed time is 2.669894 seconds.
Run Code Online (Sandbox Code Playgroud)