fill function sometimes working and sometimes not working, why?
이전 댓글 표시
I am using R2024a on a linux system.
I thought that the fill() command will fill-in a closed polygon with a given colour whether the points are in anti-clockwise order or in clockwise order. In the test script attached I have created a cubic x^3+c*x+d which has 3 real roots r(1)<r(2)<r(3) and I wish to fill-in the region above the axis with one colour and the region below the axis in another colour. I have 3 attempts in what is given in the attachment with just the second attempt working. If I change to c=-2.4 and dfac=0.11 then all 3 cases work. For most choices of the parameters all 3 cases give the same graphics.
There are no warnings or messages when fill() does not do anything.
Is there something that needs to be done to ensure that fill() always works? I guess that I can always give both orders of the points but this will mostly seem to be unnecessary.
채택된 답변
추가 답변 (1개)
Seems trivial to me. (Ok, easy. Triviality is in the eye of the beholder.) I don't give a hoot about how many real roots it has, or their locations.
fcd = @(x,c,d) x.^3 + c*x + d;
f = @(x) fcd(x,-2.4,0.11);
fplot(f,'k-',[-2,2])
grid on
x = [-2,linspace(-2,2,1000),2];
ypos = max(f(x),0);
ypos([1,end]) = 0;
yneg = min(f(x),0);
yneg([1,end]) = 0;
hold on
fill(x,ypos,'g')
fill(x,yneg,'r')
I never looked at your code, but from what you said, I'll conjecture you were trying too hard, worrying about things like root locations, etc. Sometimes you need to just step back and gain a better focus on the problem.
댓글 수: 3
Michael
2025년 8월 10일
John D'Errico
2025년 8월 10일
편집: John D'Errico
2025년 8월 10일
What can I say? I showed how to solve your problem, without even needing to worry about the roots. It works nicely, in a very few lines of code. But if this was a homework assignment, well, it is your issue to deal with. You never did tell us the parameters of the assignment, and why you wanted to solve it that way. Honestly, solving for the roots is a poor approach, in the sense that it forces you to do much more work. But an assignment typically dictates how you should solve it. You will get better help if you are forthcoming with what is needed.
Michael
2025년 8월 10일
카테고리
도움말 센터 및 File Exchange에서 Graphics Object Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!












