plot values MATLAB table with conditions
41 views (last 30 days)
Show older comments
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/800809/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/800814/image.png)
0 Comments
Accepted Answer
Dave B
on 15 Nov 2021
Edited: Dave B
on 15 Nov 2021
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
0 Comments
More Answers (1)
See Also
Categories
Find more on Scatter Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!