Function in M file doesnt recognize the variable L defined in the command window

조회 수: 1 (최근 30일)
When I make a function call in the command window by making vector argument X by writing Lx(X)which is defined in M file as follows:
function [Lx]= Lx(X) diff(L,X) return
end
it gives me following error message:
""""""""Undefined function or variable 'L'.
Error in Lx (line 2) diff(L,X)""""""""""
Although I had defined the function L as L=L= x1^2+x2^2+u1^2+u2^2; and X=[x1 x2], in the command window, it is happening. Please help out.Kinda urgent.Please
Thanks
  댓글 수: 1
upinderjeet
upinderjeet 2013년 3월 23일
Disregard ..please....I am now able to use gradient functions in the command window itself and as Wayne King said I dont need separate mfile functions as my functions are not complicated.

댓글을 달려면 로그인하십시오.

답변 (2개)

Wayne King
Wayne King 2013년 3월 23일
편집: Wayne King 2013년 3월 23일
You need to have L as an input argument in your function. Functions do not reach into the command window to read variables there. You must provide them as inputs.
And don't name your output variable the same name as your function. The same is true of just working at the command line, you don't want to name variables the same name as functions.
So your function definition should be something like:
function Lprime = Lx(L,X)
Lprime = diff(L,X);
end
Although I'm not sure why you need a function for that symbolic differentiation, just do it at the command line.
Finally, your syntax:
diff(L,[x1 x2])
is not going to work. Read the help for diff()
  댓글 수: 2
upinderjeet
upinderjeet 2013년 3월 23일
Thanks for the quick reply first of all.Appreciate this.
The following command help diff() did not work when I entered it in the command window. I was trying to work on what you said about creating functions in the command window itself rather than separate mfile. How can I do that. 2nd question: If I define X=[x1 x2] and give X some value like say X=[1 2], then do I have to pass the argument as "X" or "[x1 x2]"??? please help
upinderjeet
upinderjeet 2013년 3월 23일
I just tried using the following code after I defined L=2*X and defined X as global variable before that. The following happens:
Lx=diff(L,X) Error using diff Difference order N must be a positive integer scalar.
Why I am not getting the desired answer as Lx=2

댓글을 달려면 로그인하십시오.


Wayne King
Wayne King 2013년 3월 23일
I told you that your syntax would not work:
"Finally, your syntax:
diff(L,[x1 x2])
is not going to work. Read the help for diff()"
You have to be clear on what result you expect here.
syms X
L = 2*X;
Lx = diff(L,X);
Produces the answer you expect, 2.
Note you must have the Symbolic Toolbox for this symbolic differentiation.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by