plotting piecewise functions with logarithm

2 views (last 30 days)
cgo
cgo on 27 Jan 2015
Answered: John D'Errico on 27 Jan 2015
I am plotting a piecewise function as in below:
x_axis=[-40:0.01:40];
g=5;
if x_axis<0;
plot(x_axis, (1/40).*log(2.*(g-10)./x_axis))
else x_axis>0;
plot(x_axis, (1/40).*log(2.*(g+10)./x_axis))
xlim([2.*(g-10) 2.*(g+10)])
ylim([0 0.2])
end
The thing is, I get an error message "Warning: Imaginary parts of complex X and/or Y arguments ignored > In pcwise at 8 "
And the graph does not show the correct plots. (How could there by complex values for a log function?) Please help. Thanks

Answers (2)

Youssef  Khmou
Youssef Khmou on 27 Jan 2015
If the input vector X is negative, log produces complex result. Try the following version :
x=[-40:0.01:40];
g=5;
if x<0;
f1=(1/40).*log(2.*(g-10)./x);
plot(x,abs(f1))
else
f2=(1/40).*log(2.*(g+10)./x);
plot(x_axis,abs(f2))
xlim([2.*(g-10) 2.*(g+10)])
ylim([0 0.2])
end

John D'Errico
John D'Errico on 27 Jan 2015
How could there be complex values for a log function? Um, what is the log(-2)? Or ANY negative number for the argument?
log(-2)
ans =
0.693147180559945 + 3.14159265358979i
So what are you doing?
log(2.*(g-10)./x_axis)
g is 5, and x_axis varies from -40 to 40.
So to me, it looks like you are trying to evaluate the log of a negative number.
Part of your problem arises from the fact that an if statement does NOT apply separately to every member test you give it. For example, this does not do what you apparently think it does:
x = 1:10;
if x < 5
stuff
else
otherstuff
end
Perhaps you are confusing it with something that does do what you want:
for x = 1:10
if x < 5
stuff
else
otherstuff
end
end
In the first example I showed, x is a vector. In the second, x is a scalar, that sequentially takes on values from 1 to 10.

Categories

Find more on Performance and Memory 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!