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