Sum specific elements of an array without using loop

조회 수: 3 (최근 30일)
Alex P
Alex P 2021년 10월 14일
댓글: Mathieu NOE 2021년 10월 14일
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.
  댓글 수: 2
Alex P
Alex P 2021년 10월 14일
Thanks a lot Mathieu. Seems that it is working perfectly.
Mathieu NOE
Mathieu NOE 2021년 10월 14일
My pleasure !

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by