Sum specific elements of an array without using loop
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Alex P
am 14 Okt. 2021
Kommentiert: Mathieu NOE
am 14 Okt. 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.
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 Kommentare
Bjorn Gustavsson
am 14 Okt. 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...
Akzeptierte Antwort
Mathieu NOE
am 14 Okt. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!