I have a function that is "vectorized". I did that because I wanted to have one such function for each value of the parameter "a":
clc;
clear all;
tic;
a=[1/2,1/3,1/4];
p = @(x) 1/3.*(exp(x.^(a))-1)./(exp(x.^(a))+1) ;
I want to have the three plots (one for each value of "a") in the same figure. However, I am having trouble isolating each function for plotting. For instance, I expected that:
p1 = @(x) p(x,1,1)
would represent one of functions, but it doesn't. My other attempts have also failed. How can I get the desired result?

 Réponse acceptée

Star Strider
Star Strider le 24 Déc 2014
Modifié(e) : Star Strider le 24 Déc 2014

1 vote

The easiest way is to pass ‘a’ as a parameter as well:
a=[1/2,1/3,1/4];
p = @(x,a) 1/3.*(exp(x.^(a))-1)./(exp(x.^(a))+1) ;
p1 = p(x,a(1));
Not that within the function, ‘a’ is whatever you want it to be. If you define it as a parameter, it will not pick up the value of ‘a’ from the workspace.

4 commentaires

John
John le 24 Déc 2014
Modifié(e) : John le 24 Déc 2014
I suppose you meant:
p1 = @(x) p(x,a(1));
It does work. I could even get the plot without the auxiliary function "p1", like:
ezplot(@(x) p(x,a(1)),[0,1])
ETA: It seems that I would need the auxiliary "p1" if I use "plot" instead of "ezplot".
Actually, I meant it as I wrote it. It works with a vector ‘x’ and whatever value you want to give it for ‘a’. (I test all my code before I post it to be sure it works. If I can’t test it, I note that it is ‘untested code’.) Your version of it will work as well, with:
p2 = p1(x);
If you used plot instead of ezplot, you would plot it as:
x = linspace(0,1);
figure(1)
plot(x, p1(x))
So long as you define ‘a’ in ‘p1’ as you have, that will work.
If you want to be elaborate:
figure(1)
for k1 = 1:length(a)
plot(x, p(x,a(k1)))
hold on
ar{k1} = sprintf('a = %s',rats(a(k1),3));
end
grid
legend(ar, 'Location','SE')
John
John le 24 Déc 2014
Modifié(e) : John le 24 Déc 2014
You've already helped a lot. But if I don't put "@(x)"I get an error message:
clc;
clear all;
tic;
a=[1/2,1/3,1/4];
p = @(x,a) 1/3.*(exp(x.^(a))-1)./(exp(x.^(a))+1) ;
p1 = p(x,a(1));
%p2 = p1(x);
Gives me:
Undefined function or variable 'x'.
Error in Untitled2 (line 9) p1 = p(x,a(1));
Thank you. I do my best!
Now I understand what you’re doing. If you only want it as a function of ‘x’, you have to specify it as you did:
p1 = @(x) p(x,a(1));
It all depends on how you want to call your function. There are at least a few ways to do it correctly, so choose the one that works best for you in your application. I chose the way I usually do it in my two versions of the plot call.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Axes Appearance dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by