MATLAB: How to sum a specific range of values in a column

matrix manipulationsum

Hello,
I'm trying to build a function that would read all the elements in a column matrix "a" then find the same value in column matrix "b" read the exact row and lastly sum all rows from exact row to exact row-30, and make it save all the answers in a new matrix.
This is what I have so far, but something is wrong.
function [psum, nsum] = datac (a, b, c)
lngth=length(a);
for i=1:lngth
eyear=a(i, 1);
row=find(b(:,1)==eyear);
row2=row-30;
psum(1,i)=sum(c(row2:row, 1) >0);
nsum(1,i)=sum(c(row2:row, 1) <0);
end

Best Answer

A few notes first. 1) Avoid length, it's a dangerous function. Use numel or size with an explicit dimension. 2) There's no point indexing the singleton dimension with vectors, a(i) is simpler and clearer than a(i, 1) for vectors. 3) Use meaningful variable names.
Assuming that your election dates are stored as datenum or datetime (preferable), then:
%variables:
%electiondates: datenum or datetime vector
%datedif: datenum or datetime vector (or better column of a table)
%difrence: numeric vector (or better column of a table)
[~, daterows] = ismember(electiondates, datedif); %find location of each election date in datedif. Assumes all dates are found
positivesum = zeros(size(electiondates));
negativesum = zeros(size(electiondates));
for row = 1:numel(daterows))
summationdifrence = difrence(max(1, daterows(row)-29) : daterows(row)); %assume you want 30 elements (hence -29). makes sure you don't go before the first element with max
positivesum(row) = sum(summationdifrence(summationdifrence> 0));
negativesum(row) = sum(summationdifrence(summationdifrence< 0));
end