Compute cumulative sum of a column vector without for loop

T
Travis · Mar 8, 2021 · 1.8K views
Question
For each index of a column vector , I want to compute the sum from index to index+spacing. spacing is an integer.   My aim is not to use for-loop but I didn't manage to find a way to avoid it:   A=(1:10)'; % column vector spacing = 4; % scalar solution = zeros(length(A)-spacing,1); for index=1:length(A)-win % equals 6 in this example solution(index)=sum(A(index:index+spacing)); end solution =     15 20 25 30 35 40  
Expert Answer
Profile picture of Neeta Dsouza
Neeta Dsouza PhD Expert
Answered Aug 12, 2026
The filter() command is one way:
 
 
tmp = filter(ones(1,spacing+1),1,A);
solution = tmp(spacing+1:end)
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!