在x轴上的y值以不同的颜色绘制
在这里,我绘制了((2*x。^2+3*exp(-x) - (100*a))。 9*x-42)-10
带有输入a = 3
,dx = 0.1
。
我想绘制蓝色的所有正y值和红色的所有负y值:
a = input('Please input a: ');
dx = input('Input step size dx: ');
if dx<0
fprintf('dx must be a non-negative number.');
while(dx<0)
dx = input('Input step size dx: ');
end
end
clf;
x = -10:dx:10;
y = ((2*x.^2+3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10
plot(x,y)
ylim([-100,100])
绘制红色的蓝色和负面Y-VALUE的正面Y-值,我尝试初始化正Y值及其域的向量,以及负Y值及其域的相同矢量。
s = size(y);
x_1 = [];
x_2 = []; %negative
y_1 = [];
y_2 = []; %negative
for i = 1:s(2)
if(y(i) >0)
x_1 = [x_1,x(i)];
y_1 = [y_1,y(i)];
elseif (y(i) <0)
x_2 = [x_2,x(i)];
y_2 = [y_2,y(i)];
end
end
s_x1 = size(x_1);
s_x1_lim = s_x1(2);
s_x2 = size(x_2);
s_x2_lim = s_x2(2);
plot(x_1,y_1,'b');
xlim([x_1(1), s_x1_lim]);
hold on
plot(x_2,y_2,'r');
xlim([x_2(1), s_x2_lim]);
hold on;
xlim([-10,10])
ylim([-100,100]);
问题是,这种方法留下了一些重叠,我宁愿不拥有。我该如何更改?
Here I've plotted ((2*x.^2+3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10
with input a=3
, dx=0.1
.
I would like to plot all positive y-values in blue and all negative y-values in red:
a = input('Please input a: ');
dx = input('Input step size dx: ');
if dx<0
fprintf('dx must be a non-negative number.');
while(dx<0)
dx = input('Input step size dx: ');
end
end
clf;
x = -10:dx:10;
y = ((2*x.^2+3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10
plot(x,y)
ylim([-100,100])
To plot positive y-values in blue and negative y-values in red, I've tried initializing vectors for positive y-values and their domain, and the same vectors for negative y-values and their domain.
s = size(y);
x_1 = [];
x_2 = []; %negative
y_1 = [];
y_2 = []; %negative
for i = 1:s(2)
if(y(i) >0)
x_1 = [x_1,x(i)];
y_1 = [y_1,y(i)];
elseif (y(i) <0)
x_2 = [x_2,x(i)];
y_2 = [y_2,y(i)];
end
end
s_x1 = size(x_1);
s_x1_lim = s_x1(2);
s_x2 = size(x_2);
s_x2_lim = s_x2(2);
plot(x_1,y_1,'b');
xlim([x_1(1), s_x1_lim]);
hold on
plot(x_2,y_2,'r');
xlim([x_2(1), s_x2_lim]);
hold on;
xlim([-10,10])
ylim([-100,100]);
Problem is, this approach leaves some overlap which I would prefer not to have. How can I change this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以制作两个数组:
neg_x = x; neg_x(neg_x&gt; 0)= nan
使用'r'
绘图,然后是正值的相反。但是,这将使您有两个阵列之间的零件,即您的差距。您可以通过找到它们并将索引扩展到一个:使用
nan
在这里有所帮助,因为MATLAB会在绘图时自动忽略这些条目,即留出一个良好的差距,而不是直线。结果:
You can make two arrays:
neg_x = x; neg_x (neg_x >0) = nan
plot using'r'
and then the opposite for the positive values. This will, however, leave you with the pieces between the two arrays, i.e. your gaps. You can correct them by finding them and extending the index by one:Using
nan
is a little help here, since MATLAB will automatically ignore those entries when plotting, i.e. leaving a nice gap, rather than a straight line.Results in: