How to plot exact user defined function?

조회 수: 5 (최근 30일)
Agniswar
Agniswar 2014년 3월 25일
편집: Serge Boisse 2018년 10월 27일
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?

채택된 답변

Walter Roberson
Walter Roberson 2014년 3월 25일
if x > 0
means
if all(x > 0)
so if you pass in a vector of x then if any x in the vector is <= 0 then the "if" will not be true.
You should research logical indexing.
  댓글 수: 1
Agniswar
Agniswar 2014년 3월 25일
Then what can I do to plot a composite function?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Serge Boisse
Serge Boisse 2018년 10월 27일
편집: Serge Boisse 2018년 10월 27일
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.

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by