为什么这段数模代码反复调试后仍然出错?

2 visualizaciones (últimos 30 días)
Dimlights
Dimlights el 18 de Jul. de 2024
Respondida: sai charan sampara el 18 de Jul. de 2024
问题是
MATLAB代码为
% 求f(x)
syms x;
f=exp(-x.^2).*(1-x.^2);
df=diff(f,x);
d2f=diff(df,x);
disp(d2f);
% 设立测试点
NN=[6,11,21,41,81];
% 初始化
a=-1;b=1;
U=zeros(81,5);
X=zeros(81,5);
for i=1:5
N=NN(i);
%网格划分
h=(b-a)/(N-1);
x=(a:h:b)';
X(1:N,i)=x;
% 真解以及fx
u_exact=exp(-x.^2).*(1-x.^2);
f=-d2f+df;
% 创建差分方程的系数矩阵
c1=2/h/h;
c2=-1/h/h;
c3=-1/h/h;
d=[c2*ones(1,N-2),0];
e=[1,c1*ones(1,N-2),1];
g=[0,c3*ones(1,N-2)];
A=diag(d,-1)+diag(e,0)+diag(g,1);
%创建右端项
rhs=f(2:end-1);
U(1)=0;
U(N)=0;
U(2:end-1,i)=A\rhs;
end
% 绘图
plot(x,u_exact,'-k*',X(1:6,1),U(1:6,1),'-ro',X(1:11,2),U(1:11,2),'-bd',X(1:21,3),U(1:21,3),'-gs',X(1:41,4),U(1:41,4),'-ch',X(1:81,4),U(1:81,4),'-mx');
title('The Solution Comparasion');
xlabel('x');
ylabel('u');
legend('exact','N=6','N=11','N=21','N=41','N=81');
报错为
错误使用 \ (第 437 行)
Invalid operands.
出错 exam1 (第 39 行)
U(2:end-1,i)=A\rhs;
对照例题
NN=[6,11,21,41,81]; a=0;b=1; U=zeros(81,5); X=zeros(81,5);
for i=1:5
N=NN(i);
h=(b-a)/(N-1);
x=(a:h:b)'; X(1:N,i)=x;
f=16.*pi.*pi.*sin(4.*pi.*x);
u_exact=sin(4.*pi.*x);
%% 创建差分方程的系数矩阵
c1=2/h/h;
c2=-1/h/h;
c3=-1/h/h;
d1=[1,c1*ones(1,N-2),1];
a1=[c2*ones(1,N-2),0];
c1=[0,c3*ones(1,N-2)];
A=diag(a1,-1)+diag(d1)+diag(c1,1); % -1表示左下次对角线, 1表示左上次对角线.
%% 创建差分方程的右端项
rhs=f;
rhs(1)=0;
rhs(N)=0;
%% 求解差分方程
U(1:N,i)=A\rhs;
end
plot(x,u_exact,'-k*',X(1:6,1),U(1:6,1),'-ro',X(1:11,2),U(1:11,2),'-bd',X(1:21,3),U(1:21,3),'-gs',...
X(1:41,4),U(1:41,4),'-ch',X(1:81,5),U(1:81,5),'-mx');
title('The Solution Comparasion');
xlabel('x'); ylabel('u');
legend('exact','N=6','N=11','N=21','N=41','N=81');

Respuestas (1)

sai charan sampara
sai charan sampara el 18 de Jul. de 2024
Hello,
In the first code in the line "f=-d2f+df" the variables "-d2f" and "df" are symbolic expressions so the variable "f" that is created is also a symbolic expression. Hence when you are trying to index through "f" in the line "rhs=f(2:end-1)" , "rhs" is being returned as an empty "sym" object and hence causing an error in the line "U(2:end-1,i)=A\rhs".
To correct this you need to substitute the values of "x" in the expression for "f" by using "subs" command in MATLAB. Applying "vpa" function over it will return the numeric array that you require in the calculation. The following code might help you:
syms x;
f=exp(-x.^2).*(1-x.^2);
df=diff(f,x);
d2f=diff(df,x);
N=6;
a=-1;
b=1;
h=(b-a)/(N-1);
x1=(a:h:b)';
X(1:N)=x1;
u_exact=exp(-x1.^2).*(1-x1.^2);
f=-d2f+df;
disp(f)
f1=subs(f,x,x1)
f1 = 
vpa(f1)
ans = 
rhs=f1(2:end-1)
rhs = 

Categorías

Más información sobre Symbolic Math Toolbox en Help Center y File Exchange.

Productos


Versión

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by