Error 'undefined function or variable' occurs even when the variable is defined
7 views (last 30 days)
Show older comments
This is my program:
f=[0 0 0 0 0 0 0 0 0 0 0];
f=f';
n=1:0.1:10;
m=1;
for count = 0:1:10
m=m+1;
f(m,1) = ((n(m)-n(m-1))/6)*(-pi*sin(pi*n(m-1))*basis1(n(m-1),n(m),n(m-1))+...
4*(-pi*sin(pi*(n(m)+n(m-1))/2))*basis1((n(m)+n(m-1))/2, n(m),n(m-1))+...
(-pi)*(sin(pi*(n(m))))*basis1(n(m),n(m),n(m+1))) + ...
((n(m+1)-n(m))/6)*(-pi*sin(pi*n(m))*basis2(n(m+1),n(m),n(m+1))+...
4*(-pi)*sin(pi*(n(m+1)+n(m))/2)*basis2((n(m+1)+n(m-1))/2,n(m), n(m+1))+...
(-pi)*sin(pi*n(m+1))*basis2(n(m+1), n(m), n(m+1)));
end
And this is the basis1 function:
function [u1]=basis1(x1, x2, x3)
u1 = (n(m) - n(m-1)) / (n(m)-n(m-1));
return
This is the error I get:
Undefined function or variable 'm'.
Error in basis1 (line 2)
u1 = (n(m) - n(m-1)) / (n(m)-n(m-1));
Error in Load_vector (line 7)
f(m,1) = ((n(m)-n(m-1))/6)*(-pi*sin(pi*n(m-1))*basis1(n(m-1),n(m),n(m-1))+...
Why is the variable 'm' undefined when it clearly holds a value from the loop? Please let me know what I must do to fix this.
0 Comments
Answers (2)
Walter Roberson
on 1 Dec 2015
functions can only see variables outside their workspace if the variables are declared global or if the function is a nested function and the variable is defined in an outer nesting function. You are defining the variable at the command prompt, outside of any function, so basis1 cannot possibly be a nested function (and nested functions would need an extra 'end' statement in them.)
If you want basis1 to know the value of m, pass m in to basis1.
Why are you bothering to pass any parameters to basis1 if you are going to ignore the parameters inside the function?
Please note that when you call a function with a parameter, the value of the parameter gets transferred in that position and becomes available under the name of the variable in the corresponding position in the "function" line for the function. The name of variables passed as parameters is sometimes available, but never when an expression is passed . So when you call
basis1(n(m-1),n(m),n(m-1))
the value n(m-1) becomes available as x1 inside the function, but the name 'n(m-1)' is not going to be available and n(m-1) cannot be accessed inside the function... but x1 can be.
2 Comments
Thorsten
on 1 Dec 2015
You should define your function basis1 in terms of its parameters x1, x2, x3, like
function [u1]=basis1(x1, x2, x3)
u1 = (x1 - x2) / (x1 - x3);
or whatever function basis1 is supposed to compute.
0 Comments
See Also
Categories
Find more on Whos 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!