Speed up MATLAB code

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Speed up MATLAB code



In my code, I have a line where I calculate the cumulative sum of a vector, A, using the cumsum() function in MATLAB (R2017b). However, between each iteration, only one element in the vector A changes, and so really it's only the values from that point onwards that change. I was wondering if there was a faster way of doing this? I have tried A(elementNumber:end) = A(elementNumber:end) - oldValue + newValue, but this isn't any faster.



Additionally, I then use the find() function at each iteration to find the first index in this cumulative sum matrix where the value first exceeds a certain value.



I was wondering if there was a faster way to perform either of these in MATLAB?



An example of the kind of code I am using is given below:


beta = 0.05;
S = randi(130, 15000, 1); I = randi(130, 15000, 1);
tmax = 10000; n=1; t(1) = 0; t1=0;
rates = (beta.*S.*I); cums = cumsum(rates); numI = sum(I);
Rtot = cums(end);
n=1; t(1) = 0; t1=0;
while t1<tmax
if n>1
newRate = beta*S(eventHouseNum)*I(eventHouseNum);
% rates(eventHouseNum) = beta*S(eventHouseNum)*I(eventHouseNum);
cums(eventHouseNum:end) = cums(eventHouseNum:end) - rates(eventHouseNum) + newRate;
rates(eventHouseNum) = newRate
end
Rtot = cums(end);
if Rtot==0
return
end
randNums = rand(2,1);
dt=-log(randNums(1))/Rtot;
P=randNums(2)*Rtot;
eventHouseNum = find(cums>=P,1);
S(eventHouseNum) = S(eventHouseNum)-1;
I(eventHouseNum) = S(eventHouseNum)+1;
numI = numI+1; n=n+1;
t(n)=t(n-1)+dt; t1=t(n);
Iarray1(n) = numI;
end





@Wolfie I've added a shortened example of the code. Is that okay, or is there still too much there?
– user112495
Aug 10 at 14:26






Profile your code, then check what makes it slow.
– Ander Biguri
Aug 10 at 15:05





@AnderBiguri I know it's definitely the cumsums and the finds that are taking up the majority of the time (along with generating the random numbers - but there's nothing I can do about that).
– user112495
Aug 10 at 15:12






@user112495 you can then probably produce a considerably smaller code for us to test
– Ander Biguri
Aug 10 at 15:14





@AnderBiguri I've produced something a bit simpler. In the above example, about 50% of the time is spent on cumsum(), and about 40% on find().
– user112495
Aug 10 at 15:35










By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard