How to vectorized the following for loop code?

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

 Respuesta aceptada

Jan
Jan el 22 de Mzo. de 2017
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?

2 comentarios

Pooja Patil
Pooja Patil el 22 de Mzo. de 2017
f is a function.for example:
f=@(t,u)(t.^(4-0.1))/(gamma(5-0.1))-u;
Jan
Jan el 22 de Mzo. de 2017
@Pooja: Please note that the gamma function is very expensive. Do not use it to calculate constants repeatedly.

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 20 de Mzo. de 2017

Editada:

el 10 de Oct. de 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by