Borrar filtros
Borrar filtros

How to vectorize this code?

2 visualizaciones (últimos 30 días)
AKSHAY PUJARI
AKSHAY PUJARI el 6 de Mayo de 2020
Editada: Sindar el 6 de Mayo de 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

Respuesta aceptada

Sindar
Sindar el 6 de Mayo de 2020
Editada: Sindar el 6 de Mayo de 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);

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by