Hello how do I plot plot function exp^(-x), x <= 0 and exp^(x), x >0, Thanks alot!
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Kristy Kwok
le 25 Mar 2018
Réponse apportée : Walter Roberson
le 25 Mar 2018
Hello how do I plot plot function exp^(-x), x <= 0 and exp^(x), x >0, Thanks alot!
This is what I have:
x = 0:0.1:10; y1=exp(-x); y2=exp(x); plot(x,y1,x,y2)
Réponse acceptée
KALYAN ACHARJYA
le 25 Mar 2018
x=-10:0.1:10;
y1=exp(-x);
plot(x,y1);
hold on;
y2=exp(x);
plot(x,y2);
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/180442/image.jpeg)
1 commentaire
Walter Roberson
le 25 Mar 2018
This is not correct. Consider x = -2, then according to the problem definition since x < 0, y = exp(-x) which is exp(-(-2)) which is exp(2) -- and only exp(2), no exp(-2) involved. Each x has exactly one y, not two y values.
Plus de réponses (5)
Kristy Kwok
le 25 Mar 2018
Modifié(e) : Walter Roberson
le 25 Mar 2018
1 commentaire
Walter Roberson
le 25 Mar 2018
No, this is no right.
- You do not plot with negative x.
- the equations from the question are set up such that exp() of a negative number is never taken, but you take exp(-x) for positive x.
Kristy Kwok
le 25 Mar 2018
Modifié(e) : Walter Roberson
le 25 Mar 2018
1 commentaire
Walter Roberson
le 25 Mar 2018
Your plot has no negative x values.
If you use abs(x) you do not need two different functions.
Kristy Kwok
le 25 Mar 2018
Modifié(e) : Walter Roberson
le 25 Mar 2018
2 commentaires
Walter Roberson
le 25 Mar 2018
Yes, like that.
The symmetry of it is not apparent because you are going only to 3 to the left of x = 0 but to 10 to the right of x = 0.
Walter Roberson
le 25 Mar 2018
Sigh. Once more with making the different ranges explicit:
x = -3 :0.1:10;
y1 = zeros(size(x));
for K = 1 : length(x)
this_x = x(K);
if this_x < 0
y1(K) = exp(-this_x);
else
y1(K) = exp(this_x);
end
end
%Which can also be written as
y2 = zeros(size(x));
mask = x < 0;
y2(mask) = exp(-x(mask));
y2(~mask) = exp(x(~mask));
%and can also be written
x = -3 :0.1:10;
y3 = exp(abs(x));
subplot(1,4,1)
plot(x, y1);
title('loop')
subplot(1,4,2)
plot(x, y2)
title('logical indexing');
subplot(1,4,3)
plot(x, y3)
title('abs()')
subplot(1,4,4)
plot(x, y1-y2, 'b*-', x, y1-y3, 'g.-')
title('difference between methods. Yes, it is EXACTLY 0')
legend('loop minus mask', 'loop minus abs')
fprintf('maximum difference between loop and mask: %g\n', max(abs(y1-y2)));
fprintf('maximum difference between loop and abs: %g\n', max(abs(y1-y3)));
fprintf('maximum difference between mask and abs: %g\n', max(abs(y2-y3)));
0 commentaires
Voir également
Catégories
En savoir plus sur Line Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!