plot values MATLAB table with conditions

29 次查看(过去 30 天)
I'm not good at Matlab, I'm trying to read from the table and do a scatter plot depending on Var1 values, ie for example if the values of Var1 is < 600 the X, Y scatter should be colored read, otherwise the color should be yellow. Please help.
Matlab code and new.xlsx are attached

采纳的回答

Dave B
Dave B 2021-11-15
编辑:Dave B 2021-11-15
The mistake here is thinking about this as an if statement, instead you want to use what people often call logical indexing. In general, you can take a vector and refer to a subset of it using another vector of false and true (or 0 and 1). And you can calculate those logical (true/false) vectors with comparison operators like <.
Here's a look at that in action with a similar dataset as what you describe:
X = randn(1000,1);
Y = randn(1000,1);
Var1 = rand(1000,1) * 1000; % so that some of the values are greater than 600 and some are not
figure(1)
scatter(X(Var1<600),Y(Var1<600),'r')
hold on
scatter(X(Var1>=600),Y(Var1>=600),'g')
Now let's do the same thing with a table:
figure(2)
t=table(X,Y,Var1);
scatter(t.X(t.Var1<600),t.Y(t.Var1<600),'r')
hold on
scatter(t.X(t.Var1>=600),t.Y(t.Var1>=600),'g')
Finally, I thought it might be worth pointing out, that scatter accepts a color input, and we could use that too so that there's just one call to scatter. This has the advantage that the points are plotted as they appear in the table, rather than plotting the green ones 'on top' of the red ones.
figure(3)
c=t.Var1<600;
scatter(t.X,t.Y,[],c)
colormap([1 0 0;0 1 0]); % scatter will use the colormap to choose colors for the values in c, so we need to tell it to use red and green

更多回答(1 个)

Mbamara Wague
Mbamara Wague 2021-11-15
This is totally clear, thank you so much!

类别

Help CenterFile Exchange 中查找有关 Scatter Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by