# Sum specific elements of an array without using loop

1 view (last 30 days)
Alex P on 14 Oct 2021
Commented: Mathieu NOE on 14 Oct 2021
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.
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 CommentsShowHide 1 older comment
Alex P on 14 Oct 2021
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 on 14 Oct 2021
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.
##### 2 CommentsShowHide 1 older comment
Mathieu NOE on 14 Oct 2021
My pleasure !

R2021b

### Community Treasure Hunt

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

Start Hunting!