I believed I almost finish the last question of the project. However, there is an error appear on line 5 in my code; " Undefined function or variable 'x' in question 3 of the project. ", I had tried to used x(i), xi or x. But still appears same

2 次查看(过去 30 天)
function [u]=
bvp_robin_finite_difference(n,f,a,b,alpha,beta,gamma,a1,b1,g1,a2,b2,g2)
A=zeros(n+1,n+1); %Create a zeros matrix with size n+i * n+1
for j=2:n % Since the test program is using i, therefore
% I used j
% here instead
A(j,j-1)=(-beta*x(i)*h-2*gamma);
A(j,j)=(2*alpha*h^2+4*gamma*x(i)^2); % I tried to created sparse
A(j,j+1)=(beta*x(i)*h-2*gamma*x(i)^2); % matrix here
end
A(1,1)=(2*a1*h-3*b1);
A(1,2)=(4*b1);
A(1,3)=(-b1);
A(n+1,n-1)=(b2);
A(n+1,n)=(-4*b2);
A(n+1,n+1)=(2*a2*h+3*b2); % this is the whole value of matrix A
% the following is the value of matrix b
f=f*2*h;
f([1,end])=[2*h*g1,2*h*g2];
B=f;
u=A\B;
end
And here is the test program.
clear
a = -pi/3;
b = pi/3;
n = 128;
h = (b-a)/n;
alpha = 2;
beta = 3;
gamma = 4;
a1 = 2;
b1 = 3;
g1 = a1*sin(a)+b1*cos(a);
a2 = 4;
b2 = -5;
g2 = a2*sin(b)+b2*cos(b);
x = zeros(n+1,1);
for i = 1:n+1
x(i) = (i-1)*h+a;
end
u_exact = sin(x);
f = alpha*sin(x)+beta*x.*cos(x) + gamma*x.*x.*sin(x);
u = bvp_robin_finite_difference(n,f,a,b,alpha,beta,gamma,a1,b1,g1,a2,b2,g2);
error_3 = norm(u-u_exact,inf)
The error : Undefined function or variable 'x'.
Error in bvp_robin_finite_difference (line 9) A(j,j-1)=(-beta*x(i)*h-2*gamma);

采纳的回答

Stephen23
Stephen23 2017-4-20
编辑:Stephen23 2017-4-20
This is your code, neatened up to make it clearer:
function u = bvp_robin_finite_difference(n, f, a, b, alpha, beta, gamma, a1,b1,g1,a2,b2,g2)
A = zeros(n+1,n+1);
for j = 2:n
A(j,j-1) = (-beta*x(i)*h-2*gamma);
...
end
So there is not input x to this function, and you do not define x at the beginning of the fucntion, but then on line A(j,j-1)... you try to access, x, which clearly does not exist in the workspace.
You are basically doing this:
function fun(a,b)
c = 1;
Z = d;
Which will be an error: the variable d does not exist in the function workspace! Yes, every function has its own workspace, and no, that value of x that you define in the base workspace is not visible in the function workspace (and this is exactly how it should be):
Solution: You need to pass x as a function input.
  2 个评论
Stephen23
Stephen23 2017-4-20
@kingsely: I hope it helped. Remember that accepting the answer that best resolves your original question is an easy way for you to show your appreciation of our (volunteer) efforts, and also shows others that your question has been resolved.

请先登录,再进行评论。

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by