Azzera filtri
Azzera filtri

How to create a piecewise function using if and else statements?

27 visualizzazioni (ultimi 30 giorni)
I am trying to plot over an interval of -5 <= x <= 5 with the following conditions:
if x <= -3 then y = -x -3;
if -3 < x < 0 then y = x + 3;
if 0 < x < 3 then y = -2.*x + 3;
if x >= 3 then y = 0.5.*x - 4.5;
This is what I have:
x = -5:5
if x <= -3
y = -x -3;
elseif x > -3 & x < 0
y = x + 3;
elseif x > 0 & x < 3
y = -2.*x + 3;
elseif x >= 3
y = 0.5.*x - 4.5;
end
plot(x,y)
I get often get errors saying "Operands to the and && operators must be convertible to logical scalar values." Most of the time, however, it will give me unhelpful answers like:
x =
Columns 1 through 10
-5 -4 -3 -2 -1 0 1 2 3 4
Column 11
5
All I want to do is plot a piecewise with if/ elseif/ etc. statements.

Risposte (3)

Torsten
Torsten il 13 Mar 2018
x = -5:5
for i=1:numel(x)
if x(i) <= -3
y(i) = -x(i) -3;
elseif (x(i) > -3) && (x(i) < 0)
y(i) = x(i) + 3;
elseif (x(i) > 0) && (x(i) < 3)
y(i) = -2*x(i) + 3;
elseif x(i) >= 3
y(i) = 0.5*x(i) - 4.5;
end
end
plot(x,y)
Best wishes
Torsten.

A Mackie
A Mackie il 13 Mar 2018
Im not sure how you are receiving that error without using '&&' or '||' in your code. But the issue with what you are doing is that you are always using the full 'x' vector whenever you are setting y - in whichever part of your if statements pass.
You don't need to use if statements necessarily to do the piecewise and could just use logical indexing. For your example this would look a little like:
x = -5:5
y = zeros(size(x)) % this creates the y vector to be same size
y(x<= -3) = -x(x<=-3) -3; %this selects only the points when x <= -3
y(x> -3 & x <0) = x(x>-3 & x<0) + 3
y(x > 0 & x < 3) = -2.*x(x > 0 & x < 3) + 3;
y(x>=3) = 0.5.*x(x>=3) - 4.5;
plot(x,y)
By placing the logic into the indexing we gather a vector the same length as x that is a list of true false values. When true we select those values and act only on these.
Is this what you are looking for or do you require IF statements to be used?

Rik
Rik il 13 Mar 2018
Or without a loop:
x=-5:5;
y=NaN(size(x));%pre-allocate to NaN so you notice it if some values are outside all your conditions
cond=x <= -3;
y(cond) = -x(cond) -3;
cond= -3 < x & x < 0;
y(cond) = x(cond) + 3;
cond= 0 < x & x < 3;
y(cond) = -2.*x(cond) + 3;
cond=x >= 3;
y(cond) = 0.5.*x(cond) - 4.5;

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by