How can I get the sum of every 3 elements of array?
6 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
BhaTTa
2024-10-21
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!