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

6 vues (au cours des 30 derniers jours)
John Go
John Go le 9 Fév 2018
Réponse apportée : BhaTTa le 21 Oct 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?

Réponses (1)

BhaTTa
BhaTTa le 21 Oct 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.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by