Plotting piece-wise functions with absolute value????

4 Ansichten (letzte 30 Tage)
Michelle
Michelle am 8 Dez. 2014
Bearbeitet: David Young am 8 Dez. 2014
Hi, I want to plot this piece-wise function:
f(x) = { x if -5<=x<=5 x^2 if x<-5 or x>5
I started out how I've plotted piece-wise functions in the past, with a for-loop and if statemnts
x = linspace (-10,10,100)
for k = 1: length(x)
if (x(k) >= -5 & x(k)<=5)
y(k) = abs(x)
elseif (x(k)<-5 | x(k)>2)
y(k) = x.^2
end
end
plot (x,y)
I keep getting this error:
In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in piecewise (line 6) y(k) = x.^2;
I cannot figure out how to plot this particular equation. Please help?

Antworten (2)

Youssef  Khmou
Youssef Khmou am 8 Dez. 2014
The algorithm you wrote is almost correct, inside the if conditions you need to use x(k), not x :
x = linspace (-10,10,100);
for k = 1: length(x)
if (x(k) >= -5 && x(k)<=5)
y(k) = abs(x(k));
elseif (x(k)<-5 || x(k)>2)
y(k) = x(k).^2;
end
end
plot (x,y)
There are other methods to generate piece wise functions.

David Young
David Young am 8 Dez. 2014
Bearbeitet: David Young am 8 Dez. 2014
To fix your existing code, with the loop, you need
y(k) = abs(x(k));
and
y(k) = x(k).^2;
Your condition x(k) > 2 in the elseif line looks wrong - it isn't what you say you want to do at the start, and it isn't consistent with the else condition. Assuming it should be x(k) > 5, you should simply replace the whole elseif line with "else".
Alternatively, you can just use MATLAB's vectorisation capability to avoid the loop altogether. Replace the loop with:
middlePart = x >= -5 & x <= 5;
y(middlePart) = abs(x(middlePart));
y(~middlePart) = x(~middlePart) .^ 2;
Note the difference between this and the looping version. With the loop, you operate on x(k), which is a scalar. With the vectorised version you operate on vectors.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by