1

I want to simply plot a function with two different styles before and after a specific value. For example, for -2*pi<= x <0 with line width of 1 and for 0<= x <=2*pi with line width 2. I have written

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

But it doesn't work

2
  • It's been a while since I did this. Perhaps try putting "hold on" before the loop, and removing 'hold' from the loop (in both if and else clauses).... Commented Apr 26, 2018 at 18:38
  • I think what your code does now is plot each point independently for each iteration of the for loop. This means LineWidth will not change the appearance of your plot as you are just plotting points. If you were to make each of your plot commands plot in a different color instead of different line width you can see the difference between x<0 and x>0 but they are just points, not a line. You would need to remove your "hold" calls from inside the if statements though and put just one "hold on" call at the end of the for loop (between the last 2 end statements) to see what I'm talking about. Commented Apr 26, 2018 at 19:05

2 Answers 2

3

There's no need to loop, just define vectors of boolean values to define the regions:

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);

If you want points rather than a connected line then use,

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);
Sign up to request clarification or add additional context in comments.

Comments

0

Your code is almost complete. You just needed to define the axis before hand. Here is the modified version.

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;

However, @Phil's method will be faster.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.