How to add differentiate a point on my graph using a for loop

1 次查看(过去 30 天)
Iam trying to have points in CG_X turned into a red color when its less than -15 or greater than 15 when I plot it on the graph using a for loop, but the end result gives me the standard blue color which is want i want when CG_X is greater than or equal to -15 and less than or equal to 15.
CG_X=[13.8 18 18.8 -5.7 2.2 -11.1 -6.3 12.4 -10.5 15.6];
CG_Y=[4.2 -13.2 -8 -11.3 11.2 1.5 -5.0 8 -7.1 19.7];
hold on;
for k=length(CG_X)
if k>15||k<-15
plot(CG_X,CG_Y,'r*');
elseif k
plot(CG_X,CG_Y,'b*');
end
end
hold off;

采纳的回答

Manan Mishra
Manan Mishra 2018-4-3
A few points to note:
1. "for k = length(CG_X)" would assign only a single value of 10 to 'k'. You need 'k' to take all values from 1 to 10.
2. While checking the condition in if-statement, you want to check the value of an element in CG_X indexed by k, not k itself.
3. "plot(CG_X,CG_Y,'r*');" would plot all the points in one go in red color. You need to plot only one point in each run of the for loop.
The following code incorporates the above mentioned changes:
CG_X=[13.8 18 18.8 -5.7 2.2 -11.1 -6.3 12.4 -10.5 15.6];
CG_Y=[4.2 -13.2 -8 -11.3 11.2 1.5 -5.0 8 -7.1 19.7];
hold on;
for k=1:length(CG_X)
if CG_X(k)>15||CG_X(k)<-15
plot(CG_X(k),CG_Y(k),'r*');
else
plot(CG_X(k),CG_Y(k),'b*');
end
end
hold off;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by