Filter löschen
Filter löschen

How to fill color between two curves?

29 Ansichten (letzte 30 Tage)
Aditya Zade
Aditya Zade am 28 Sep. 2023
Kommentiert: Aditya Zade am 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

Akzeptierte Antwort

Star Strider
Star Strider am 28 Sep. 2023
Bearbeitet: Star Strider am 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 Kommentare
Star Strider
Star Strider am 28 Sep. 2023
As always, my pleasure!
Aditya Zade
Aditya Zade am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Mathieu NOE
Mathieu NOE am 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)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by