How to plot a piece-wise function using FPLOT

조회 수: 6 (최근 30일)
Ali Remo
Ali Remo 2017년 1월 29일
댓글: Star Strider 2017년 1월 29일
Hello Please state if possible, how to use fplot to have the graph of a piecewise function. Actually the code below is exactly according to the matlab page: https://uk.mathworks.com/help/matlab/ref/fplot.html
fplot(@(x) exp(x),[-3 0],'b')
hold on
fplot(@(x) cos(x),[0 3],'b')
hold off
grid on
But, it does not work for me. The code plots only the second function, cos(x). Please help me if possible.

채택된 답변

Star Strider
Star Strider 2017년 1월 29일
편집: Star Strider 2017년 1월 29일
It is easiest to use ‘logical indexing’ in your function.
This works:
f = @(x) exp(x).*(x<=0) + cos(x).*(x>0);
figure(1)
fplot(f, [-3, 3])
grid
EDIT The code you posted actually works for me without error, producing the correct plot. The online documentation is for the current release (that I believe is still R2016b), so if you have an earlier version, that could be a problem. My code should work.
  댓글 수: 6
Ali Remo
Ali Remo 2017년 1월 29일
@Star Strider , Thank you very much for your help. Yes actually the main code contains functions which are continuous in continuous intervals. The code above which I wrote was only to say what my problem is actually. In each interval I have a different function, but finally they generate a continuous function, for example:
in the interval [0 1] ....... f1(x) = x
in the interval [1 2] ....... f2(x) = x^2
.
.
.
and as you can see, these two samples are continuous at the point x=1. The point is that I have to produce these function in a FOR LOOP and plot them in a single graph. Thank you
Star Strider
Star Strider 2017년 1월 29일
My pleasure.
If my Answer helped you solve your problem, please Accept it.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by