How do I plot this? MATLAB

让人想犯罪 __ 提交于 2019-12-12 04:50:04

问题


I have a matrix, X, in which I want to plot it using the kmeans function. What I would like: If row has a value of 1 in column 4 I would like it to be square shaped If the row has a value of 2 in column 4 I would like it + shaped BUT If the row has a value of 0 in column 5 it must be blue and if the row has a vale of 1 in column 5 it must be yellow

(You don't need to use these exact colors and shapes, I just want to distinguish these.) I tried this and it did not work:

plot(X(idx==2,1),X(idx==2,2),X(:,4)==1,'k.');

Thanks!!


回答1:


Based on the example on the kmeans documentation page I propose this "nested" logic:

X = [randn(100,2)+ones(100,2);...
     randn(100,2)-ones(100,2)];
opts = statset('Display','final');

% This gives a random distribution of 0s and 1s in column 5: 
X(:,5) = round(rand(size(X,1),1));

[idx,ctrs] = kmeans(X,2,...
                    'Distance','city',...
                    'Replicates',5,...
                    'Options',opts);

hold on
plot(X(idx==1,1),X(idx==1,2),'rs','MarkerSize',12)
plot(X(idx==2,1),X(idx==2,2),'r+','MarkerSize',12)

% after plotting the results of kmeans, 
% plot new symbols with a different logic on top:

plot(X(X(idx==1,5)==0,1),X(X(idx==1,5)==0,2),'bs','MarkerSize',12)
plot(X(X(idx==1,5)==1,1),X(X(idx==1,5)==1,2),'gs','MarkerSize',12)
plot(X(X(idx==2,5)==0,1),X(X(idx==2,5)==0,2),'b+','MarkerSize',12)
plot(X(X(idx==2,5)==1,1),X(X(idx==2,5)==1,2),'g+','MarkerSize',12)

The above code is a minimal working example, given that the statistics toolbox is available.
The key feature is the nested logic for the plotting. For example:

X(X(idx==1,5)==0,1)

The inner X(idx==1,5) selects those values of X(:,5) for which idx==1. From those, only values which are 0 are considered: X(X(...)==0,1). Based on the logic in the question, this should be a blue square: bs.
You have four cases, hence there are four additional plot lines.



来源:https://stackoverflow.com/questions/17602230/how-do-i-plot-this-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!