For loop time consuming
조회 수: 22 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (1개)
Image Analyst
2017년 6월 17일
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
Image Analyst
2017년 6월 17일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!