How to vectorize this code?

1 view (last 30 days)
AKSHAY PUJARI
AKSHAY PUJARI on 6 May 2020
Edited: Sindar on 6 May 2020
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

Accepted Answer

Sindar
Sindar on 6 May 2020
Edited: Sindar on 6 May 2020
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);

More Answers (0)

Categories

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

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!