Plot function in two intervals
조회 수: 4 (최근 30일)
이전 댓글 표시
I'm trying to plot an interval funciton like,
This is the code that I used
x = -3:0.001:3;
a = 1.3;
y = zeros(size(x));
for i = 1: length(x)
if (x(i) >= -a && x(i)<=a)
y(i) = 0.5*x(i).^2;
else
y(i) = a*abs(x(i))-a^2;
end
end
plot (x,y)
But it did not plot this result.
댓글 수: 0
채택된 답변
Image Analyst
2021년 11월 28일
Try this (following your non-vectorized approach):
x = -4 : 0.001 : 4;
a = 1.3;
y = zeros(size(x));
for k = 1: length(x)
if abs(x(k)) < a
y(k) = 0.5*x(k).^2;
else
y(k) = a*abs(x(k))- 0.5 * a^2;
end
end
plot (x, y, 'r-', 'LineWidth', 2)
grid on;
If you want a vectorized approach:
x = -4 : 0.001 : 4;
a = 1.3;
y = a*abs(x)- 0.5 * a^2;
innerX = abs(x) < a;
y(innerX) = 0.5*x(innerX).^2;
plot (x, y, 'r-', 'LineWidth', 2)
grid on;
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Line Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!