How to define and plot a piecewise function using if/elseif
8 ビュー (過去 30 日間)
古いコメントを表示
Iakovos Antonoglou
2018 年 6 月 18 日
コメント済み: Walter Roberson
2018 年 6 月 18 日
Hello, i am trying to define and plot a piecewise fucntion specifically using if/elseif. The function is
f(x)=1,sin(x)>=1/2 f(x)=-1,sin(x)<=-1/2 f(x)=0,elsewise
I've trying using syms or function but i seem to be ending up with a problem, most commonly being any function i try to define inside an if gives me an error "x function not defined"
My latest attempt that produces no error but still doesnt work is
function gga(x)
x=linspace(0,4*pi)
if sin(x)>=1/2
y=1
elseif sin(x)<=-1/2
y=-1
else y=0
end
plot(x,y)
end
0 件のコメント
採用された回答
Walter Roberson
2018 年 6 月 18 日
Symbolic form:
syms x
f(x) = piecewise(sin(x) >= 1/2, 1, sin(x) <= -1/2, -1, 0);
fplot(f, [0 4*pi])
Numeric form:
y = zeros(size(x));
sx = sin(x);
mask = sx <= -1/2;
y(mask) = -1;
mask = sx >= 1/2;
y(mask) = 1;
It is also possible to construct it as a single numeric expression, but that takes a bit of thinking.
2 件のコメント
Walter Roberson
2018 年 6 月 18 日
In order to do this using if/elseif/else you will need to loop over the elements.
for idx = 1 : length(x)
if sin(x(idx)) ...
その他の回答 (1 件)
Ankita Bansal
2018 年 6 月 18 日
編集済み: Ankita Bansal
2018 年 6 月 18 日
Hi Iakovos, the solution given by Walter can be rewritten as
x=linspace(0,4*pi);
y = zeros(size(x));
y(sin(x) <= -1/2) = -1;
y(sin(x) >= 1/2) = 1;
plot(x,y)
However, if you want to use if/else in your code then you can do this as
function gga
x=linspace(0,4*pi);
l=numel(x);
for i=1:l
if sin(x(i))>=1/2
y(i)=1;
elseif sin(x(i))<=-1/2
y(i)=-1;
else y(i)=0;
end
end
plot(x,y)
end
1 件のコメント
参考
カテゴリ
Help Center および File Exchange で Line Plots についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!