multiple plots with colors of a function in matlab

To plot multiple plots with different colors of a function in Matlab, you can do the following:

  1. Define your function. Let's say your function is y = sin(x).
  2. Define the range of x values over which you want to plot the function.
  3. Define an array of different colors that you want to use for the plots.
  4. Use a loop to generate the plots, with each plot using a different color from the color array.

Here's an example code snippet that demonstrates this:

main.m
% Step 1: Define your function
y = @(x) sin(x);

% Step 2: Define the range of x values
x = linspace(0, 2*pi, 100);

% Step 3: Define an array of different colors
colors = ['r', 'g', 'b', 'm', 'c'];

% Step 4: Generate the plots
figure; % Open a new figure window
hold on; % Enable hold on to plot multiple lines on the same figure
for i = 1:length(colors)
    plot(x, y(x), colors(i));
end
hold off; % Disable hold on

% Add labels and title to the plot
xlabel('x');
ylabel('y');
title('Multiple Plots with Different Colors of a Function');

% Add a legend to show the colors
legend('Color 1', 'Color 2', 'Color 3', 'Color 4', 'Color 5');
640 chars
25 lines

Note that in the plot() function, the third argument colors(i) is used to specify the color of the plot for each iteration of the loop. The hold on and hold off commands are used to enable and disable the hold behavior, respectively, which allows multiple plots to be displayed on the same figure.

This code snippet will generate a plot with multiple lines, each line using a different color from the colors array.

related categories

gistlibby LogSnag