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

1 visualizzazione (ultimi 30 giorni)
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 Commento
upinderjeet
upinderjeet il 23 Mar 2013
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.

Accedi per commentare.

Risposte (2)

Wayne King
Wayne King il 23 Mar 2013
Modificato: Wayne King il 23 Mar 2013
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 Commenti
upinderjeet
upinderjeet il 23 Mar 2013
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 il 23 Mar 2013
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

Accedi per commentare.


Wayne King
Wayne King il 23 Mar 2013
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.

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by