Effacer les filtres
Effacer les filtres

How to fill color between two curves?

39 vues (au cours des 30 derniers jours)
Aditya Zade
Aditya Zade le 28 Sep 2023
Commenté : Aditya Zade le 28 Sep 2023
clc
clear
x(1) = 0 ;
y(1) = 0 ;
for i = 1 : 1 : 99
x(i+1) = i^2 ;
y(i+1) = 50 * i ;
end
figure(1)
plot(x)
hold on
plot(y)
grid on

Réponse acceptée

Star Strider
Star Strider le 28 Sep 2023
Modifié(e) : Star Strider le 28 Sep 2023
If you only want the region between the curves before or after they cross, use ‘logical indexing’.
Try this —
% clc
% clear
i = 1:99;
x = [0 i.^2];
y = [0 50*i];
iv = 1:numel(x);
Lv = x <= y; % Logical Vector
figure(1)
plot(x, 'LineWidth',1, 'DisplayName','x')
hold on
plot(y, 'LineWidth',1, 'DisplayName','y')
patch([iv(Lv) flip(iv(Lv))], [x(Lv) flip(y(Lv))], 'r', 'EdgeColor','none', 'DisplayName','Before Inmtersection')
patch([iv(~Lv) flip(iv(~Lv))], [x(~Lv) flip(y(~Lv))], 'g', 'EdgeColor','none', 'DisplayName','After Intersection')
hold off
grid on
legend('Location','best')
EDIT — (28 Sep 2023 at 11:25)
Æsthetic improvements.
.
  3 commentaires
Star Strider
Star Strider le 28 Sep 2023
As always, my pleasure!
Aditya Zade
Aditya Zade le 28 Sep 2023
Can you look into this as well?
https://www.mathworks.com/matlabcentral/answers/2026949-how-to-stack-up-multiple-cases-in-z-axis?s_tid=prof_contriblnk

Connectez-vous pour commenter.

Plus de réponses (1)

Mathieu NOE
Mathieu NOE le 28 Sep 2023
hello
see below
FYI, your code does not need a for loop. Take advantage of matlab native vectorized operations
% y1(1) = 0 ;
% y2(1) = 0 ;
% for i = 1 : 1 : 99
%
% y1(i+1) = i^2 ;
% y2(i+1) = 50 * i ;
%
% end
x = 0:99;
y1 = x.^2 ;
y2 = 50*x ;
figure(1)
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,[0.9 0.9 0.9]); %#plot filled area
hold on
plot(x,y1,'r',x,y2,'m','linewidth',2)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by