# What data type is valid for piecewise functions?

조회 수: 8(최근 30일)
Chase Reiter 6 Aug 2020
댓글: Chase Reiter 6 Aug 2020
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

표시 이전 댓글 수: 4
Chase Reiter 6 Aug 2020
Alan Stevens,
This script is just a tester for a bigger project I am working on. The focus of this project depends upon me using a piecewise function so I have to use the piecewise command. In the end, I won't end up using this code anyway, it's just a tester.
dpb 6 Aug 2020
Type it in at the command line to see what MATLAB returns for the piecewise function resolution.
Chase Reiter 6 Aug 2020
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 6 Aug 2020
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 6 Aug 2020
syms x
y = piecewise(x<0, -x, x>0, x);
fplot(y,'r')
axis([-10 10 -10 10])

#### 댓글 수: 1

Chase Reiter 6 Aug 2020
That also works

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

### Community Treasure Hunt

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

Start Hunting!

Translated by