Borrar filtros
Borrar filtros

How to fill color between two curves?

39 visualizaciones (últimos 30 días)
Aditya Zade
Aditya Zade el 28 de Sept. de 2023
Comentada: Aditya Zade el 28 de Sept. de 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

Respuesta aceptada

Star Strider
Star Strider el 28 de Sept. de 2023
Editada: Star Strider el 28 de Sept. de 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 comentarios
Star Strider
Star Strider el 28 de Sept. de 2023
As always, my pleasure!
Aditya Zade
Aditya Zade el 28 de Sept. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Mathieu NOE
Mathieu NOE el 28 de Sept. de 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)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by