Plot function in two intervals

조회 수: 4 (최근 30일)
NA
NA 2021년 11월 28일
답변: Image Analyst 2021년 11월 28일
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.

채택된 답변

Image Analyst
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개)

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by