Plot function in two intervals

3 次查看(过去 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.

采纳的回答

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