Hello how do I plot plot function exp^(-x), x <= 0 and exp^(x), x >0, Thanks alot!
Show older comments
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)
1 Comment
Walter Roberson
on 25 Mar 2018
hint: exp(abs(x))
Accepted Answer
More Answers (5)
Kristy Kwok
on 25 Mar 2018
Edited: Walter Roberson
on 25 Mar 2018
1 Comment
Walter Roberson
on 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
on 25 Mar 2018
Edited: Walter Roberson
on 25 Mar 2018
1 Comment
Walter Roberson
on 25 Mar 2018
Your plot has no negative x values.
If you use abs(x) you do not need two different functions.
Kristy Kwok
on 25 Mar 2018
Edited: Walter Roberson
on 25 Mar 2018
2 Comments
Walter Roberson
on 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.
Kristy Kwok
on 25 Mar 2018
Edited: Kristy Kwok
on 25 Mar 2018
Kristy Kwok
on 25 Mar 2018
0 votes
Walter Roberson
on 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)));
Categories
Find more on 2-D and 3-D Plots 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!