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

조회 수: 13 (최근 30일)
Michelle
Michelle 2014년 12월 8일
편집: David Young 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;
I cannot figure out how to plot this particular equation. Please help?

답변 (2개)

Youssef  Khmou
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.

David Young
David Young 2014년 12월 8일
편집: 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