Plot function in two intervals

3 visualizaciones (últimos 30 días)
NA
NA el 28 de Nov. de 2021
Respondida: Image Analyst el 28 de Nov. de 2021
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.

Respuesta aceptada

Image Analyst
Image Analyst el 28 de Nov. de 2021
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;

Más respuestas (0)

Categorías

Más información sobre Line Plots en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by