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

14 次查看（过去 30 天）
Michelle 2014-12-8

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;

回答（2 个）

Youssef Khmou 2014-12-8
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.
0 个评论显示 -1更早的评论隐藏 -1更早的评论

David Young 2014-12-8

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.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by