MATLAB: Cumulative sum of values if criteria is true

cumulative sumMATLAB

Hi,
I am trying to calculate a cumulative sum of the Fluid_used but only count if the vehicleSecData.Temperature is between a high and low temperature range.
I have the following code which works fine.
vehicleSecDataLength = length(vehicleSecData.Temperature)
Fluid_used = 0
for c = 1:vehicleSecDataLength
if (vehicleSecData.Temperature(c) >=170) && (vehicleSecData.Temperature(c) <190)
Fluid_used(c) = Fluid_used(end) + vehicleSecData.Fluid_used(c);
else
Fluid_used(c) = Fluid_used(end);
end
end
However, it is extremly slow as the data row length is a few tens of millions. My question is, is there a fast way to achive this using a method other than "for" "if" statement?
i am using 2019a
Cheers

Best Answer

criterion = (vehicleSecData.Temperature >=170) & (vehicleSecData.Temperature <190) ;
Fluid_used=cumsum(vehicleSecData.Fluid_used.*criterion);