I want to change the color of the markers in scatter plot which are below the function line

조회 수: 1 (최근 30일)
I have the following code
clc
clear
close all
d = 4;
N = 1000;
X = linspace(0,d,N);
func = @(X) 2*X.*cos(X.^2).*exp(sin(X.^2)) + 14;
limit = func(X);
x = 4*rand(1,N);
y = 25*rand(1,N);
figure(1),hold on
h = scatter(x,y,10,'markerfacecolor','b');
plot(X,limit,'k-','linew',1.3)
for i = 1:N
if any(y(i) < limit)
set(h,'YData','MarkerFaceColor','r','Markeredgecolor','r')
end
end
but it keeps giving the following error
Error using matlab.graphics.chart.primitive.Scatter/set
Invalid parameter/value pair arguments.
Any help would be appreciated

채택된 답변

Star Strider
Star Strider 2022년 4월 11일
d = 4;
N = 1000;
X = linspace(0,d,N);
func = @(X) 2*X.*cos(X.^2).*exp(sin(X.^2)) + 14;
limit = func(X);
x = 4*rand(1,N);
y = 25*rand(1,N);
figure(1)
hold on
scatter(x,y,10,'markerfacecolor','b');
Lv = y < func(x); % Logical Vector Based On 'func' Value At Each 'x'
scatter(x(Lv),y(Lv),10,'MarkerFaceColor','r','Markeredgecolor','r')
plot(X,limit,'k-','linew',1.3)
.
  댓글 수: 2
Haseeb Hashim
Haseeb Hashim 2022년 4월 11일
Hi Great work. Can you please explain these lines expecially the first one
Lv = y < func(x);
scatter(x(Lv),y(Lv),10,'MarkerFaceColor','r','Markeredgecolor','r')
Star Strider
Star Strider 2022년 4월 11일
Thank you!
Sure!
The ‘Lv’ variable is a logical vector that calculates the value of ‘func’ at each ‘x’ value and compares that result with the corresponding ‘y’ value. If that ‘y’ value is less than ‘func(x)’, that value of ‘Lv’ is set to true. (It definitely helps that ‘func’ is an anonymous function in your original code, making this straightforward.)
The scatter call just after that uses ‘Lv’ to refer to the individual ‘x’ and ‘y’ values, plotting only those that are true as defined by ‘Lv’.

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

추가 답변 (1개)

MJFcoNaN
MJFcoNaN 2022년 4월 11일
You can try this:
clc
clear
close all
d = 4;
N = 1000;
X = linspace(0,d,N);
func = @(X) 2*X.*cos(X.^2).*exp(sin(X.^2)) + 14;
limit = func(X);
x = 4*rand(1,N);
y = 25*rand(1,N);
ind_r = y < limit;
c=zeros(N,3);
% red
c(ind_r, 1)=1;
% blue
c(~ind_r, 3)=1;
figure(1),hold on
h = scatter(x,y,10,c);
plot(X,limit,'k-','linew',1.3)
  댓글 수: 2
Haseeb Hashim
Haseeb Hashim 2022년 4월 11일
Now I get it we cant check the particular random against every number of function value because in this case the random numbers greater than the greatest number in function values will be turned blue otherwise they will be all read
MJFcoNaN
MJFcoNaN 2022년 4월 11일
Why do you make both x and y random?
If your task allows one random value, for example x=X, it may give out a more "reasonable" result, which achieves the same algorithm as the other answer.

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

카테고리

Help CenterFile Exchange에서 Scatter Plots에 대해 자세히 알아보기

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by