plot values MATLAB table with conditions

조회 수: 13 (최근 30일)
Mbamara Wague
Mbamara Wague 2021년 11월 15일
답변: Mbamara Wague 2021년 11월 15일
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에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by