Method of finite differences

3 次查看(过去 30 天)
Melda Harlova
Melda Harlova 2019-5-10
评论: Adam 2019-5-10
Hello, i have to solve this with a method of finite differences
x'' = -2x'(t) – 2x(t) + e^(-t) + sin(2t)
t ϵ [0,4]; x(0) = 0,6; x(4) = -0,1
And here is my code in Matlab
clear all;
al=0.6; bt=-0.1; h=0.01;
t=0:h:4;
n=length(t)-2;
for i=1:n
if i~=1, a(i,i-1)=-1+h;end
a(i,i)=2-2*(h^2);
if i~=n, a(i,i+1)=-1-h;end
f(i)=-(h^2)*(exp(-t))-(h^2)*(sin(2*t(i)));
end
f(1)=f(1)-al*(-1+h);
f(n)=f(n)-bt*(-1+h);
x=a\f';
x1=[al,y',bt];
figure(1),plot(t,x1)
when i run this i get this error: Unable to perform assignment because the indices on the left side are not compatible with the size of the right side. Error in differences (line 9) f(i)=-(h^2)*(exp(-t))-(h^2)*(sin(2*t(i)));
And is my solution of the task without matlab:
x'' + 2x'(t) + 2x(t) = e^(-t) + sin(2t)
  • a = 1; b = 2; c=2; d = e^(-t) + sin(2t)
Ai,i-1 = -ai + (h/2)bi =-1 + (h/2).2=-1+h
Ai,i = 2ai – h2ci = 2.1 – 2h^2 = 2 - 2h^2
Ai,i+1 = -ai - (h/2)bi = -1 – (h/2)2 = -1 - h
fi = -h^2di = -h^2(e^(-t)+ sin(2t))
so my questions are why im getting this error and are my coeficients right.
Thanks in advance. :)
  1 个评论
Adam
Adam 2019-5-10
t is a vector, f(i) is a scalar. You should pre-declare f before the loop, but even so f(i) would still be a scalar. I imagine you probably just want to use t(i) instead of t. You do this later on on the same line, but not for the first usage.
As for the seconod question, I can't answer that with a glance at the code!

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by