필터 지우기
필터 지우기

How to fill color between two curves?

조회 수: 39 (최근 30일)
Aditya Zade
Aditya Zade 2023년 9월 28일
댓글: Aditya Zade 2023년 9월 28일
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

채택된 답변

Star Strider
Star Strider 2023년 9월 28일
편집: Star Strider 2023년 9월 28일
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
Star Strider
Star Strider 2023년 9월 28일
As always, my pleasure!
Aditya Zade
Aditya Zade 2023년 9월 28일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Mathieu NOE
Mathieu NOE 2023년 9월 28일
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)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by