Sum specific elements of an array without using loop

7 次查看(过去 30 天)
I would like to sum over specific elements of an array, but i would like to avoid loop (if it is possible).
Let's assume that i would like to create an 1x10 array ("res" array on the code below) which will store zero elements and the sum over specific elements of the "A" array in the indicators that are descriped in the "inds" array.
For example i would like to achieve res(1) = 0, res(2) = sum(A(1:7)) , res(3) = 0, res(4) = sum(A(8:15)) e.t.c., where the values "1","7","8" and "15" are stored in the arrays "S" and "E" respectively.
Is there a way to achieve this, avoiding the loop, as i try at the code below.
Thanks very much in advance.
A = [1;0;0;0;0;1;1;1;0;0;0;1;1;0;0;0;0;0;0;1;1;1;0;0;1;0;0;1;0;0]; % 30x1 Array
res = zeros(1,10);
S = [1 8 16 27];
E = [7 15 26 30];
inds = [2 4 7 10];
i = 1:length(inds); % - "Vectorized" Method
res(inds(i)) = sum(A(S(i):E(i))); % that doesn't give right results
for j=1:length(inds) % - Classic Loop that i
res(inds(j)) = sum(A(S(j):E(j))); % would like to avoid
end
  2 个评论
Bjorn Gustavsson
Bjorn Gustavsson 2021-10-14
What is your reason to want to avoid that simple loop? If your res-variable is properly pre-allocated I see no problem with that...
Alex P
Alex P 2021-10-14
The code that i posted is a simple example. In fact, inside the loop, except from the sum calculation, i would like to make calculations as matrix multiplications e.t.c., so i think that it will be faster to vectorize the loop.

请先登录,再进行评论。

采纳的回答

Mathieu NOE
Mathieu NOE 2021-10-14
hello Alex
try this
A = [1;0;0;0;0;1;1;1;0;0;0;1;1;0;0;0;0;0;0;1;1;1;0;0;1;0;0;1;0;0]; % 30x1 Array
tic
res = zeros(1,10);
S = [1 8 16 27];
E = [7 15 26 30];
inds = [2 4 7 10];
% method 1
for j=1:length(inds) % - Classic Loop that i
res(inds(j)) = sum(A(S(j):E(j))); % would like to avoid
end
toc
% method 2
% A better solution is:
tic
res2 = zeros(1,10);
cA = cumsum(A);
tmp = cA(E);
tmp2= [tmp(1); diff(tmp)];
res2(inds) = tmp2';
toc
Comparison of results :
res =
0 3 0 3 0 0 4 0 0 1
Elapsed time is 0.001069 seconds.
res2 =
0 3 0 3 0 0 4 0 0 1
Elapsed time is 0.000577 seconds.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by