MATLAB: How to vectorized the following for loop code

vectorization of for loop

for n=1:nt-1
sum1=0;
for jj=1:m-1
sum1=sum1+(t(n+1)).^jj.*u(1).^jj/factorial(jj);
end
sum2=0;
for ii=1:n
sum2=sum2+(h.^alpha).*(1/gamma(alpha+1)).*((n-ii+1).^alpha-(n-ii).^alpha).*(f(t(ii),u(ii)));
end
u(n+1)=sum1+sum2;
end

Best Answer

As in your other threads: Start with cleaning the loop. You should try to do this by your own.
u1c = u(1);
c1 = (h .^ alpha) .* (1 / gamma(alpha+1));
for n = 1:nt-1
tn1c = t(n + 1);
tn1 = 1;
u1 = 1;
fact = 1;
sum1 = 0;
for jj = 1:m-1
fact = fact * jj; % A faster factorial(jj)
tn1 = tn1 * tn1c; % A faster t(n+1)^jj
u1 = u1 * u1c; % A faster u(1) ^jj
sum1 = sum1 + tn1 .* u1 / fact;
end
sum2 = 0;
v = -diff((n:-1:0) .^ alpha);
for ii=1:n
sum2 = sum2 + c1 .* v(ii) .* f(t(ii), u(ii));
end
u(n+1) = sum1 + sum2;
end
Is f a function or a matrix?