Why is my code running for forever?

조회 수: 2 (최근 30일)
Mikayla Farr
Mikayla Farr 2018년 3월 1일
편집: Jos (10584) 2018년 3월 1일
I am using forward differencing to calculate values of Yn for the given timestep t. The first while loop outputs what I want, but it seems to get stuck on the second one. In the second while loop I am first finding the values of the analytical solution as the timestep t increases, and I am using those values to calculate the error of the analytical solutions and the solutions that used forward differencing.
clear
clc
clf
%Known Values
theta = 10;
v = 0;
t = 0.1;
%First-order system of equations
I = [1 0; 0 1];
A = [0 1; (-327/20) -4];
Yn = [theta; v];
%Analytical Solution
x = 0;
T = linspace(0,6,1000);
theta1 = 10*exp(-2*x)*cosd((1/2)*sqrt(247/5)*x) + 5.691103933*exp(-2*x)*sind((1/2)*sqrt(247/5)*x);
subplot(2,1,1)
plot(T,theta1,'k','LineWidth',2);
hold on
%Forward Differencing at t = 0.1
Te = 0;
i = 1;
n = 1;
Tmax = 6;
while (Te(i) <= Tmax);
Yn(:,i+1) = [I + t*A]*Yn(:,i);
Te(i+1) = Te(i) + t;
i = i + 1;
end
%Plot
subplot(2,1,1)
plot(Te, Yn(1,:),'m','LineWidth', 2);
title('Change in Angle Theta as Time Increases');
xlabel('Time (s)');
ylabel({'Angle Made by the String'; 'with the Vertical Axis';'(degrees)'});
axis([0 7 -5 12]);
Te = ones(1,62);
theta11 = ones(1,62);
%error
while (Te(n) <= Tmax)
theta11(n) = 10*exp(-2*Te(n))*cosd((1/2)*sqrt(247/5)*Te(n)) + 5.691103933*exp(-2*Te(n))*sind((1/2)*sqrt(247/5)*Te(n));
error1 = abs(theta11- Yn(1,:));
Te(n+1) = Te(n) + t;
end
%Find Max Error and plot it
M1 = max(error1)

답변 (1개)

Jos (10584)
Jos (10584) 2018년 3월 1일
편집: Jos (10584) 2018년 3월 1일
You never change n inside the second while loop
→ T(n) never changes
T(n) <= Tmax always evaluates to true
→ infine loop ...
btw, you also overwrites error1 all the time
(very buggy code ..)

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by