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

1 Ansicht (letzte 30 Tage)
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;

Akzeptierte Antwort

Image Analyst
Image Analyst am 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 Kommentare
Image Analyst
Image Analyst am 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)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by