Clear Filters
Clear Filters

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

3 views (last 30 days)
function [u]=
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)=(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
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
And here is the test program.
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;
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);

Accepted Answer

Stephen23 on 20 Apr 2017
Edited: Stephen23 on 20 Apr 2017
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);
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.
Stephen23 on 20 Apr 2017
@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.

Sign in to comment.

More Answers (0)


Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!