How to plot Peicewise functions?
이전 댓글 표시
Hello there!
I am trying to script the following:
f(x)={x^2 0<=x<=1/2 && 1/2(1-x) for 1/2<x<1
and plot for 0<x<5
..................
Having tried :
function f = f_x(x)
if x<1/2
f=x^2
else if x<1
f=1/2(1-x)
else
f=0
end
this function to create the conditions how would I go to plot it?
댓글 수: 1
Walter Roberson
2013년 12월 3일
Be sure to correct
f=1/2(1-x)
to
f=1/2*(1-x)
or
f=1/(2*(1-x))
as appropriate... your notation is ambiguous.
답변 (2개)
Walter Roberson
2013년 12월 3일
xvals = linspace(0, 5, 101); %plot at 101 points
y = zeros(size(xvals));
for K = 1 : length(xvals)
y(K) = f_x(xvals(K));
end
plot(xvals, y);
댓글 수: 2
Kevin
2013년 12월 3일
Walter Roberson
2013년 12월 3일
The linspace(0, 5, 101) part says to choose values evenly spaced from 0 to 5 inclusive. If you want the 0 and 5 excluded, drop the first and last values of the array.
That function is not periodic. If you want it to be periodic, use
function f = f_x(X)
x = mod(X, 1);
SANJU HAZRA
2020년 10월 16일
편집: SANJU HAZRA
2020년 10월 16일
syms x
p = piecewise((0<=x<=0.5),x^2,(0.5<x<1),0.5*(x-1))
fplot(p,[0 5])
댓글 수: 1
Walter Roberson
2020년 10월 16일
편집: Walter Roberson
2020년 10월 16일
Note that piecewise() is one of the very few places in MATLAB where you can use range comparisons in that form LB <= x <= UB . In nearly all other contexts, LB <= x <= UB is interpreted as ((LB <= x) <= UB) where the first test returns a logical value and the logical value is compared to UB.
Another place that you can use LB <= x <= UB is in solve() .
The key is not exactly that the expression is symbolic: if you enter
0<=x<=0.5
at the command line then you will get back
(0 <= x) <= 1/2
Because this kind of range test works in so few places, I recommend against using it in code, as it could lead to people getting the wrong impression that such range tests are generally valid in MATLAB. It is not uncommon for people to write these kinds of range tests and to run into trouble because of it.
카테고리
도움말 센터 및 File Exchange에서 Noncentral t Distribution에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!