Sum specific elements of an array without using loop

4 views (last 30 days)
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 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 14 Oct 2021
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 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.

Sign in to comment.

Accepted Answer

Mathieu NOE
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.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!