Plot function in two intervals

3 vues (au cours des 30 derniers jours)
NA
NA le 28 Nov 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.

Réponse acceptée

Image Analyst
Image Analyst le 28 Nov 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;

Plus de réponses (0)

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by