1 view (last 30 days)

f=@(t,u) t*(u^.2-u+0.5);

[tv,uv]=BE(f,1,10,100);

function [tv, uv] = BE(f, u0, T, n)

dt = T/n; % Differential of time.

tv = transpose(0:dt:T); % Evaluation times.

uv = zeros(n+1, 1); % Solution.

uv(1) = u0; % Initial value

for i=1:length(tv)-1

uv(i+1) = uv(i) + f(tv(i+1), uv(i+1))*dt;

end

end

This is a problem that I was trying to solve on Matlab grader, what am I missing or what did I do wrong in here? This is Backward Euler.

John D'Errico
on 4 Jul 2020

Thank you. That makes it much easier for someone to offer you help. Now I'll be willing to look at the problem you had.

It looks like you took the code you wrote for an Euler solve, and then just tried changing this line:

uv(i+1) = uv(i) + f(tv(i+1), uv(i+1))*dt;

As you can (should) see, this is a problem, because it presumes a value on the right hand side, thus uv(i+1), that at that point in the loop, has never been assigned. So, what does MATLAB use there? It uses the zero value you put in that place before the loop ever started, when you preallocated uv as zeros. That is, for every iteration, you caused this to happen:

uv(i+1) = uv(i) + f(tv(i+1), 0)*dt;

And that clearly is NOT what you wanted.

I think you missed the part of the question, where they even prompted you with the trick you need to use. It said to use fzero. (Reread the last line of the question as you give it.) At that point, you don't know the value of uv(i+1). But you do have an equation for it. The value uv(i+1) is the value that satisfies the equation:

uv(i) + f(tv(i+1), uv(i+1))*dt - uv(i+1) = 0

So you need to use fzero to find that value. How would your code change? Almost everything stays the same.

f=@(t,u) t*(u^.2-u+0.5);

[tv,uv]=BE(f,1,10,100);

function [tv, uv] = BE(f, u0, T, n)

dt = T/n; % Differential of time.

tv = transpose(0:dt:T); % Evaluation times.

uv = zeros(n+1, 1); % Solution.

uv(1) = u0; % Initial value

for i=1:length(tv)-1

uv(i+1) = fzero(@(uvsol) uv(i) + f(tv(i+1), uvsol)*dt - uvsol, uv(i));

end

end

Do you see what the for loop now does? Inside the loop, it uses fzero each time, solving for the unknown value of uv(i+1), such that the equation is satisfied.

To choose the starting value for fzero it at each iteration, I used uv(i), based on the assumption that uv(i+1) should be close to uv(i).

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Direct link to this comment

https://la.mathworks.com/matlabcentral/answers/559424-what-am-i-missing-here#comment_924650

⋮## Direct link to this comment

https://la.mathworks.com/matlabcentral/answers/559424-what-am-i-missing-here#comment_924650

## Direct link to this comment

https://la.mathworks.com/matlabcentral/answers/559424-what-am-i-missing-here#comment_924665

⋮## Direct link to this comment

https://la.mathworks.com/matlabcentral/answers/559424-what-am-i-missing-here#comment_924665

Sign in to comment.