basic question on creating a function and plotting

1 view (last 30 days)
Hello everyone
i have the expression to calculate: Ke=K0*e*a*(a-1)/(1+e-a*e)
K0, e are known values and a is my variable so i create the function Ke(a).
But using the command: Ke1=inline('K0*e*a*(a-1)/(1+e-a*e)') does not apply the given values of K0 and e, that is, it returns the function Ke1(K0,e,a), instead of Ke1(a)
I am using MATLAB 2009b
Thanks in advance

Accepted Answer

Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh on 14 Aug 2014
Edited: Salaheddin Hosseinzadeh on 14 Aug 2014
Hi Vaggelis,
How about using anonymous function?
f = @(k0,e,a) k0.*e.*a.*(a-1)./(1+e-a.*e)
then you can easily evaluate f by making a range for a, lets say -10 < a < 10 and keep k0 and e constant, lets assume k0 is 1 and e is 2 so you can use f as f(1,2,a)
a = -10:.1:10;
plot(a,f(1,2,a));
hope this helps. Good luck!
  3 Comments
Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh on 14 Aug 2014
I also considered that you wanna change their value in the future so that I suggested this solution.
Although I made a mistake in the code, defining the anonymous function. I missed a @ sign
If you define your function as
f = @(k,e,a)
in fact you're making them all independent variables, so f is a function k e and a and you may change their value anytime. you may change k e a and get different answeres.
Salaheddin Hosseinzadeh
Salaheddin Hosseinzadeh on 14 Aug 2014
It would be a good practice to use inline, when the equation is to be given by the user.
In your case your equation is fixed! You probably don't need to use inline or anonymous function, I don't know what your intention is but I guess you can just write the code free of any complexity and getting involve function definition and get your satisfactory response, don't confuse your self!

Sign in to comment.

More Answers (1)

Amir
Amir on 14 Aug 2014
Please try this code and compare the results:
disp('%%%%% Run1 %%%%%%');
syms K0 e a;
F=K0*e*a*(a-1)/(1+e-a*e);
Ke1=matlabFunction(F)
disp('%%%%% Run2 %%%%%%');
K0=2; e=2.71;
syms a;
F=K0*e*a*(a-1)/(1+e-a*e);
Ke1=matlabFunction(F)
Results are as below:
%%%%% Run1 %%%%%%
Ke1 =
@(K0,a,e)(K0.*a.*e.*(a-1.0))./(e-a.*e+1.0)
%%%%% Run2 %%%%%%
Ke1 =
@(a)(a.*(a-1.0).*(-2.71e2./5.0e1))./(a.*(2.71e2./1.0e2)-3.71e2./1.0e2)

Categories

Find more on Function Creation 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!