Effacer les filtres
Effacer les filtres

For loop time consuming

13 vues (au cours des 30 derniers jours)
Arbol
Arbol le 17 Juin 2017
Modifié(e) : Arbol le 17 Juin 2017
Is there a way to rewrite this code? If I go to tdata(i) = 100, the iteration loop would have to go through 100/h=100/0.1=1000 loops, or at tdata(i)=200, the loop would have to go through 2000 loops. Is there a way to keep or memorize the previous loop rather than start over again?
tdata is time, and it increases.
function tout = grabvalue(p,tdata,tu)
for i=1:length(tdata)
out(i) = RK4(p,tdata(i),tu);
end
tout = out;
end
function Tissue_single = RK4(p,tfinal,tu)
h=0.1;
F=p(1); fp=p(2); fis=p(3); PS=p(4);
if tfinal == 0
N=1;
else
N=ceil(tfinal/h);
end
t=zeros(1,N);
y=zeros(2,N);
f=@(t,y) [...
(F/fp)*(interpn(tu(:,1),tu(:,2),t)-y(1))-(PS/fp)*(y(1)-y(2));
(PS/fis)*(y(1)-y(2))];
%------------------- RK4 Loop-----------------------------------%
for i=1:N
% Update t
t(i+1)=t(i)+h;
%Update equation
k1 = f(t(i) ,y(:,i) );
k2 = f(t(i)+0.5*h, y(:,i)+ 0.5*k1*h);
k3 = f(t(i)+0.5*h, y(:,i)+ 0.5*k2*h);
k4 = f(t(i)+h , y(:,i)+k3*h);
y(:,i+1) = (y(:,i) + h/6 *(k1 + 2*k2 + 2*k3 + k4));
end
Tissue= y(1,:)*fp+y(2,:)*fis;
Tissue_single=Tissue(end);
end

Réponses (1)

Image Analyst
Image Analyst le 17 Juin 2017
A for loop of 1000 or 2000 iterations is not time consuming. The computations inside the loop may be time consuming but the for loop itself is not. I just did a for loop with 100 million iterations and it took only 0.2 seconds so don't worry about an extremely miniscule 1000 iterations. We're talking millionths of a second for that few iterations.
Anyway, I don't know what "memorize the previous loop" means so I don't know what to tell you.
  5 commentaires
Image Analyst
Image Analyst le 17 Juin 2017
I'm getting it to run in 0.38 seconds. See attached program.
tdata =
10 20
tout =
10.7411530699029 190.22825510961
Elapsed time is 0.381234 seconds.
Arbol
Arbol le 17 Juin 2017
Modifié(e) : Arbol le 17 Juin 2017
Can you try tdata=tu(:,1)? This will take a lot longer.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by