How can I get the sum of every 3 elements of array?

7 visualizaciones (últimos 30 días)
John Go
John Go el 9 de Feb. de 2018
Respondida: BhaTTa el 21 de Oct. de 2024
Hallo, how can I get the sum of every 3 elements of an large array in an efficient way without using a for loop?
%
%I have an array with 30 elements
A = [11:40]
%
%What I want is an array B with 10 elements
B(1) = sum(A(1:3))
B(2) = sum(A(4:6))
B(3) = sum(A(7:9))
B(4) = sum(A(10:12))
%....
%with the result
B
%B = [36 45 54 63 ....
%...
How can I do this in an efficient way?

Respuestas (1)

BhaTTa
BhaTTa el 21 de Oct. de 2024
Hey @John Go, you can achieve it by using 'reshape' function. The idea is to reshape your array into a matrix where each column contains the elements you want to sum, and then use the sum function to compute the sums along the columns
Below I have attched the code for the same:
% Define the array
A = 11:40;
% Reshape the array into a 3-row matrix
% Each column will have 3 elements from A
reshapedA = reshape(A, 3, []);
% Sum along each column
B = sum(reshapedA, 1);
% Display the result
disp('B =');
disp(B);
Hope it helps.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by