Matlab中修改一维泊松方程右侧表达式遇语法错误求助
一维泊松方程有限差分实现的语法错误修正
核心问题定位
你的代码中右侧表达式的写法存在三处关键错误:
- 语法错误:Matlab不支持隐式乘法,
2x必须写成2*x; - 数组索引错误:
x是整个网格坐标数组,你需要取当前网格点的坐标值x(j),而非直接使用数组x; - 表达式不匹配:你当前写的是
2x,但题目要求的右侧是2x² - 0.5x + exp(x),需要完全对应。
修正后的完整代码
% Solving of 1D Poisson equation % using finite differences % Clearing memory and figures clear all clf % Define 1D numerical model xsize=100; % Model size in horizontal direction, m Nx=101; % Number of grid points dx=xsize/(Nx-1); % Gridstep, m x=0:dx:xsize; % Coordinates of grid points, m % Defining global matrixes L=zeros(Nx,Nx); % Coefficients in the left part R=zeros(Nx,1); % Right parts of equations % Composing global matrixes % by going through all grid points for j=1:1:Nx % Discriminating between BC-points and internal points if(j==1 || j==Nx) % BC-points (Dirichlet boundary condition Φ=0) L(j,j)=1; % Left part R(j)=0; % Right part else % Composing Poisson eq. d²Φ/dx² = 2x² - 0.5x + exp(x) % ---Φ(j-1)------Φ(j)------Φ(j+1)---- STENCIL % 1/dx²*Φ(j-1) + (-2/dx²)*Φ(j) + 1/dx²*Φ(j+1) = 2x(j)² -0.5x(j)+exp(x(j)) % Left part of j-equation L(j,j-1)=1/dx^2; % Φ(j-1) coefficient L(j,j)=-2/dx^2; % Φ(j) coefficient L(j,j+1)=1/dx^2; % Φ(j+1) coefficient % Right part (corrected expression) R(j)=2*x(j)^2 - 0.5*x(j) + exp(x(j)); end end % Solve the linear system S=L\R; % Reload solutions (Φ corresponds to T in code) Phi=zeros(1,Nx); % Create array for Φ for j=1:1:Nx Phi(j)=S(j); end % Visualize results figure(1); clf plot(x,Phi,'ro-') % Plot with red circles and lines xlabel('x (m)') ylabel('Φ') title('1D Poisson Equation Solution')
额外优化说明
- 变量名修正:将原代码中的
T改为Phi,更贴合题目中的Φ,提升可读性; - 绘图格式修正:原
plot(x,T,'o r')不符合Matlab格式字符串规则,改为'ro-'表示红色圆圈标记+连线; - 添加了坐标轴标签和标题,让可视化结果更清晰。
内容的提问来源于stack exchange,提问作者Matlaboverflow
相关产品推荐
相关产品推荐

