The code is
syms x;
v = @(x) (4 - x^2)^(1/2) - (2 - x)^(1/2)*(x + 2)^(1/2);
ezplot(v(x),[-2,2]);
which produce a plot
Should not v(x) be zero for every x in [-2,2]?
If the idea is to replace "small" values in the output of your equation with zero, then some sort of if
condition on the output data is needed. Unfortunately, you can't add an if
to the anonymous function but you can do one of two things: define a standard function (in a program file) or wrap your anonymous function in another. The first way is more straightforward:
function [y] = v_func(x)
y = (4 - x.^2).^(1/2) - (2 - x).^(1/2).*(x + 2).^(1/2);
y(abs(y)<1e-10)=0;
end
The above performs the same calculation as before with second line of code replacing all values that are less than some tolerance (1e-10) with zero. Note how the equation is slightly different than your original one. It has been "vectorized" (see the use of the periods) to allow for an input vector to be evaluated rather than having to loop over each element in the vector. Note also that when we pass it to ezplot
we must prefix the function name with the ampersand:
ezplot(@v_func,[-2,2]);
The second way requires wrapping your first anonymous function v
in a couple of others (see anonymous functions and conditions). We start with your original function that has been vectorized:
v = @(x) (4 - x.^2).^(1/2) - (2 - x).^(1/2).*(x + 2).^(1/2);
and a (condition) function that replaces all values less than some tolerance with zero:
cond = @(y)(y*(1-(abs(y)<1e-10)))
We then wrap the two together as
func = @(x)cond(v(x))
so that the condition function evaluates the output of v
. Putting it together with ezplot
gives:
ezplot(func,[-2,2]);
and all output, as shown in the plot, should be zero.
The figure title will not be what you want, so it can be replaced with some variation of:
plotTitle = func2str(v);
title(strrep(plotTitle(5:end),'.','')); % as I don't want '@(x)' or periods to
% appear in the title
I've ignored the use of sym
as I don't have the Symbolic Toolbox.