MATLAB: How to vectorize this code

for loopMATLABperformancesumvectorization

I have the following loop.It is needed to improve the performance and hence need to vectorize the loop.Is it possible?
I am facing difficulty in vectorizing due to use of "sum" operator in line 3 and 5.
frequency=randi([0 578],110,1);
axis(:,1)=[-275:5:270];
for k=1:size(frequency,1)
if axis(k,1)<=0
cumFrequency(k,1)=sum(frequency(1:k,1));
elseif axis(k,1)>0
cumFrequency(k,1)=sum(frequency(k:end,1));
end
end
Thanks

Best Answer

frequency=randi([0 578],110,1);
axis=[-275:5:270]';
% get indices where axis is negative
axis_negative = (axis<=0);
% calculate the cumulative sum of frequency
cumFrequency_neg = cumsum(frequency);
% calculate the reverse cumulative sum of frequency
cumFrequency_pos = cumsum(frequency,'reverse');
% insert the forward and reverse sums in the indices according to axis
cumFrequency(axis_negative,1) = cumFrequency_neg(axis_negative);
cumFrequency(~axis_negative,1) = cumFrequency_pos(~axis_negative);
Related Question