How to vectorize this code?

2 次查看(过去 30 天)
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

采纳的回答

Sindar
Sindar 2020-5-6
编辑:Sindar 2020-5-6
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);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by