MATLAB: How to speed up the following code? I am using MATLAB R2018a. Thanks.

speed up. make faster.

for t = 1:T
for x = 1:X
for y = 1:Y
for w = 1:X
for z = 1:Y
p(x,y,t) = p(x,y,t) + e(x,y,w,z)*beta*M(w,z,t);
end
end
end
end
for x = 1:X
for y = 1:Y
if M(x,y,t) == 0
f(x,y,t)= 0;
else
f(x,y,t) = constant*M(x,y,t)*(1-exp(-p(x,y,t)/M(x,y,t)));
end
end
end
for x = 1:X
for y = 1:Y
for w = 1:X
for z = 1:Y
S(x,y,t) = S(x,y,t) + t(x,y,w,z)*f(w,z,t);
end
end
end
end
for x = 1:X
for y = 1:Y
M(x,y,t+1) = C*(1-exp(-S(x,y,t)*r/C));
end
end
end

Best Answer

Code blindly:
PP = reshape(p,[X*Y,T]); % p == 0?
EE = reshape(e,[X*Y X*Y]);
MM = reshape(M,[X*Y T]);
PP = PP + beta*EE*MM; %%PP = 0 before?
p = reshape(PP,[X,Y,T]);
f = constant*M.*(1-exp(-p./M));
FF = reshape(f,[X*Y T]);
TT = reshape(t,[X*Y,X*Y]);
SS = reshape(S,[X*Y,T]); %%S==0?
SS = SS + TT*FF; %%SS==0 before?
S = reshape(SS,[X,Y,T]); %%s==0?
M(:,:,2:T+1) = C*(1-exp(-S*r/C));