Summing elements of a vector without a for loop

10 views (last 30 days)
Given a vector/array v of length , I would like to create a new vector of length M where the 1st component is the sum of the 1st 5 elements of v, the 2nd element is the sum of the next 5 elements of v,... and so on until we get to the last element which is the sum of the last 5 elements of v.
Is there a quick way to do this without using a for loop?

Accepted Answer

Yongjian Feng
Yongjian Feng on 29 Oct 2021
Edited: Yongjian Feng on 2 Nov 2021
How about this:
M=3; % you know your M
v = ones(1, M^2); % your v vector
vReshaped = reshape(v, M, M)'; % Note need this.
result = sum(vReshaped, 2)';

Sign in to comment.

More Answers (1)

KSSV on 29 Oct 2021


Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!