What data type is valid for piecewise functions?

4 ビュー (過去 30 日間)
Chase Reiter
Chase Reiter 2020 年 8 月 6 日
コメント済み: Chase Reiter 2020 年 8 月 6 日
I am trying to graph a simple piecewise function.
Basically, I am trying to graph:
for x < 0, y = -x,
for x>0, y = x.
My code looked like this:
x = -10:1/100:10;
y = piecewise(x<0, -x, x>0, x);
plot(x,y,'r')
axis([-10 10 -10 10])
But when I attempt to do it using the piecewise command, I get this message:
Undefined function 'piecewise' for input arguments of type 'double'.
So after that I tried using the cast command to change the data type.
Then, my code looked like this:
x = -10:1/100:10;
b = cast(x, 'single')
y = piecewise(b<0, -b, b>0, b);
plot(b,y,'r')
axis([-10 10 -10 10])
and once again, I got
Undefined function 'piecewise' for input arguments of type 'single'.
And I tried this for all data types and it didn't work. What am I missing?
Here is my code:
% This plots the x-axis
x = -100:1/100:100;
y = 0*x;
plot(x,y,'k')
hold on
%This plots the y-axis
x = -100:1/100:100;
y = 9999*x;
plot(x,y,'k')
hold on
%This is the graph
x = -10:1/100:10;
y = piecewise(x<0, -x, x>0, x);
plot(x,y,'r')
axis([-10 10 -10 10])
  7 件のコメント
dpb
dpb 2020 年 8 月 6 日
Type it in at the command line to see what MATLAB returns for the piecewise function resolution.
Chase Reiter
Chase Reiter 2020 年 8 月 6 日
When I typed which -all piecewise into the command line, I got:
C:\Program Files\MATLAB\R2019a\toolbox\symbolic\symbolic\@sym\piecewise.m % sym method

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

採用された回答

Chase Reiter
Chase Reiter 2020 年 8 月 6 日
The reason it wasn't working was because I wasn't making my function symbolic.
Here is the correct code. It works perfectly.
% This plots the x-axis
x = -100:1/100:100;
y = 0*x;
plot(x,y,'k')
hold on
%This plots the y-axis
x = -100:1/100:100;
y = 9999*x;
plot(x,y,'k')
hold on
%This is the graph
syms y(x);
y(x) = piecewise(x<0, -x, x>0, x);
fplot(y)
axis([-10 10 -10 10])

その他の回答 (1 件)

dpb
dpb 2020 年 8 月 6 日
syms x
y = piecewise(x<0, -x, x>0, x);
fplot(y,'r')
axis([-10 10 -10 10])
  1 件のコメント
Chase Reiter
Chase Reiter 2020 年 8 月 6 日
That also works

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

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by