在matlab

时间:2018-04-26 18:36:43

标签: matlab

我想简单地在特定值之前和之后绘制具有两种不同样式的函数。例如,对于线宽为1的-2*pi<= x <0和线宽为2的0<= x <=2*pi,我写了

for x=-2*pi:0.1:2*pi
   y = sin(x);
   if x < 0
     plot(x,y,'LineWidth',1)
     grid on
     hold
   else
     plot(x,y,'LineWidth',2)
     grid on
     hold
   end
end

但它不起作用

2 个答案:

答案 0 :(得分:3)

无需循环,只需定义布尔值的向量来定义区域:

x = -2*pi:0.1:2*pi;
y = sin(x);
idx_period1 = (x >= -2*pi) & (x < 0);
idx_period2 = ~[idx_period1(2:end),false]; % ensure the regions touch.
plot(x(idx_period1),y(idx_period1),'LineWidth',1);
hold on
plot(x(idx_period2),y(idx_period2),'LineWidth',2);

如果您想要点而不是连接线,请使用

idx_period1 = (x >= -2*pi) & (x < 0);
idx_period2 = ~idx_period1;
scatter(x(idx_period1),y(idx_period1),'Marker','.','MarkerSize',1);
hold on
scatter(x(idx_period2),y(idx_period2),'Marker','.','Markersize',2);

答案 1 :(得分:0)

您的代码已基本完成。您只需要预先定义轴。这是修改后的版本。

figure(1); hold on; 
axis([-2*pi 2*pi -1.5 1.5]);
for x=-2*pi:0.1:2*pi
   y = sin(x);
   if x < 0
     plot(x,y,'-o', 'LineWidth',1)
%      grid on
%      hold
   else
     plot(x,y, 'r+', 'LineWidth',2)
%      grid on
%      hold
   end
end
grid on;
hold off;

然而,@ Phil的方法会更快。