How to plot exact user defined function?
Show older comments
I have defined a function like this
function z=agni(x)
if x > 0
z=x;
else
z = x.^2;
end
But in the time of plotting plot(x,agni(x)) with x =[-2:.01:2] generate only the curve of x^2. WHY?
Accepted Answer
More Answers (1)
Serge Boisse
on 27 Oct 2018
Edited: Serge Boisse
on 27 Oct 2018
Hello, You should understand that your function accepts a vector of values, not a scalar. then it must return a vector of the same length (that will be plotted) So you may rewrite your function as follows :
function z=agni(x)
z = x; % this is a vector !
ind = (x<0); % logical array : 1 if corresponding element of x is <0
z(ind) = z(ind).^2;
end
Hope this helps. If you prefer to code functions "the classical way", have a look at symbolic functions.
Categories
Find more on Geographic 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!