Important plotting question (defining the markers in a for loop)

3 views (last 30 days)
Hi all,
If I want to run this code in a for loop and plot everything with different markers, how can I do that?
x = -2*pi:0.1:2*pi;
y1 = sin(x); y2 = sin(2*x); y3 = sin(3*x); y4 = sin(4*x); y5 = sin(5*x); y6 = sin(6*x);
plot(x,y1,'ro-'); hold on;
plot(x,y2,'bo-'); hold on;
plot(x,y3,'ko-'); hold on;
plot(x,y4,'r.-'); hold on;
plot(x,y5,'b.-'); hold on;
plot(x,y6,'k.-'); hold on;

Accepted Answer

Image Analyst
Image Analyst on 30 Jan 2023
Try it this way:
x = -2*pi:0.1:2*pi;
colors = {'r', 'b', 'k', 'r', 'b', 'k'};
markers = {'o', 'o', 'o', '.', '.', '.'};
for k = 1 : 6
y = sin(k * x);
plot(x, y, '-', 'Color', colors{k}, 'Marker', markers{k});
hold on;
end
grid on;
legend
xlabel('x', 'FontSize',15)
ylabel('y', 'FontSize',15)
  3 Comments
Image Analyst
Image Analyst on 30 Jan 2023
You can make the legend strings up like this
x = -2*pi:0.1:2*pi;
colors = {'r', 'b', 'k', 'r', 'b', 'k'};
markers = {'o', 'o', 'o', '.', '.', '.'};
for k = 1 : 6
y = sin(k * x);
plot(x, y, '-', 'Color', colors{k}, 'Marker', markers{k});
hold on;
legendStrings{k} = sprintf('Curve for y%d', k);
end
grid on;
legend(legendStrings, 'Location', 'Northwest');
xlabel('x', 'FontSize',15)
ylabel('y', 'FontSize',15)

Sign in to comment.

More Answers (0)

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!