MATLAB: Matlab matrix operations without loops

arrayfor looploopsMATLABmatrixoptimization

Hello. I have an issue with a code performing some array operations. It is getting to slow, because I am using loops. I am trying for some time to optimize this code and to re-write it with less or without loops. Until now unsuccessful. Can you please help me solve this:
YVal = 1:1:100000;
M_MAX = 1000;
N_MAX = 2000;
clear YTemp
tic
for M=1:1:M_MAX
for N = 1:1:N_MAX
YTemp(M,N) = sum(YVal (N+1:N+M) ) - sum(YVal (1:M) );
end
end
For large N_MAX and M_MAX the execution time of these two loops is very high. How can I optimize this?
Thank you,
Florin

Best Answer

Try his code, 200 faster
YVal = 1:1:100000;
M_MAX = 1000;
N_MAX = 2000;
tic
som1=zeros(1,M_MAX+N_MAX);
YTemp=zeros(M_MAX,N_MAX);
for k=1:M_MAX+N_MAX
som1(k)=sum(YVal(1:k));
end
for M=1:1:M_MAX % Number of accumulated periods
som2=som1(M+1)-YVal(1);
for N = 1:1:N_MAX % statistic
YTemp(M,N) = som2- som1(M);
som2=som2+YVal(N+M+1)-YVal(N+1);
end
end
toc
Related Question