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!