Why am I receiving unexpected result with euler function?

1 次查看(过去 30 天)
Unexpected results occur at sol variable in script.m in for loop. I would like to assign the result of eyplicit_euler2 function to sol variable. When I debug ,I receive the correct results stored in y variable in function, but when I assign the result to sol variable, value of sol at that iteration changes to 0. Could not figure out why that happens. Thanks!
.m
function ysol = explicit_euler2(t0,t1,yy)
f=@(t,y)[t*y(2); 4*(y(1)^(3/2))];
t=linspace(t0,t1,11);
n=10;
h=(t(end)-t(1))/n;
y=zeros(11,2);
y(1,:)=yy;
for i=1:n
y(i+1,:)=y(i,:)+h*f(t(i),y(i,:))';
end
ysol=y(end,:);
end
script.m
int=linspace(0,5,11);
y0=[1 0];
s=zeros(11,2);
s(1,1)=1;
s(1,2)=0;
sol=zeros(11,2);
sol(1,:)=y0;
for j=1:10
sol(j+1,:)=explicit_euler2(int(j),int(j+1),s(j,:));
end

回答(1 个)

Walter Roberson
Walter Roberson 2016-7-22
Look at
f=@(t,y)[t*y(2); 4*(y(1)^(3/2))];
and notice that if both y(1) and y(2) are 0, that the result of f will be 0.
Now look at
y(i+1,:)=y(i,:)+h*f(t(i),y(i,:))';
and see that if y(i,:) is 0 then the y passed in to f will be 0 so the result of the f call would be 0, and then to that would be added the already-zero y(i,:) . Therefore if y(i,:) is 0 in that code then your output is going to be 0. As soon as you get a 0 input pair, the result of the outputs must be 0.
Now look at
s=zeros(11,2);
s(1,1)=1;
s(1,2)=0;
and see that for all s below the first row, both pairs are 0.
Then see
sol(j+1,:)=explicit_euler2(int(j),int(j+1),s(j,:));
and see that those 0's are going to be passed in on all except the first iteration. We can see from this that after that first iteration, all of the outputs are going to be 0. Which is the behaviour you saw.

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by