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
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
Walter Roberson 2013 年 12 月 3 日

0 投票

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
Kevin 2013 年 12 月 3 日
Thanks now any idea how to plot this periodic function from 0<x<5? so there will be 5 of these waveforms on the one graph.
Walter Roberson
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
SANJU HAZRA 2020 年 10 月 16 日
編集済み: SANJU HAZRA 2020 年 10 月 16 日

0 投票

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
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.

サインインしてコメントする。

質問済み:

2013 年 12 月 3 日

編集済み:

2020 年 10 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by