strange behavior of function leading to complex numbers

1 view (last 30 days)
i have defined a function named f_gamma which is as follows:
function F = f_gamma(x,xdata)
if xdata <= x(1)
F = 0;
return;
end
F = x(2).*((xdata-x(1)).^x(3)).*exp(-(xdata-x(1))/x(4));
end
in my understanding, for every xdata<=x(1) the function should return zero. but it doesnt. let me give you an example:
lets set x (the constants) = [8, 5, 3, 0.5]; therefore, for all xdata <= 8 the function should return F = 0.
if i call the function now like this
f_gamma(x,2)
ans = 0
everything is correct.
however, if i call it like this, e.g. for plotting
f_gamma(x,1:50)
ans(2) = 229898430,869035 - 250127664,068870i
where does this complex number come from? am i missing something? your help is much appreciated. :)

Accepted Answer

dpb
dpb on 20 Aug 2014
Edited: dpb on 20 Aug 2014
if xdata <= x(1)
...
...in my understanding, for every xdata<=x(1) the function should return zero.
Your have a major mis understanding --
help if
...
The statements are executed if the real part of the expression
has all non-zero elements.
So, as written, if there are any elements in xdata>=x(1) the expression is false.
For element-by-element evaluation of your function you need something like...
F=zeros(size(xdata)); % allocate; set zero locations
ix = xdata>x(1); % logical address of "good" values
F(ix)=x(2).*((xdata(ix)-x(1)).^x(3)).*exp(-(xdata(ix)-x(1))/x(4));
Or, you could just go ahead and compute the complex values, then zero them out...
F=x(2).*((xdata-x(1)).^x(3)).*exp(-(xdata-x(1))/x(4));
F(xdata<=x(1))=0; % zero those needed to be
  1 Comment
Oliver
Oliver on 20 Aug 2014
duh. i knew i was missing something obvious, thanks, dpb! i really appreciate your code example, too.

Sign in to comment.

More Answers (1)

Adam
Adam on 20 Aug 2014
If you call
xData <= x(1)
when xData is a vector you will get a vector of results of the same length.
You need to use
all( xData <= x(1) )
if you want a single value representing that all the data in your array meet the condition.
any( xData <= x(1) )
would be the equivalent if you just want to check that at least one value meets the condition.

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!