plot 4 different variables in one graph in matlab

To plot four different variables in one graph in MATLAB, you can use the plot function multiple times within the same figure. Here is an example code:

main.m
x = 1:10;
y1 = rand(1,10);
y2 = rand(1,10);
y3 = rand(1,10);
y4 = rand(1,10);

plot(x, y1, 'b');
hold on;
plot(x, y2, 'r');
plot(x, y3, 'g');
plot(x, y4, 'm');
hold off;

legend('Variable 1', 'Variable 2', 'Variable 3', 'Variable 4');
xlabel('X-axis');
ylabel('Y-axis');
title('Plot of Four Variables');
304 chars
18 lines

In the above code, x represents the x-values, and y1, y2, y3, and y4 represent the corresponding y-values of the four variables. The plot function is used to plot each variable with different line colors, such as 'b' for blue, 'r' for red, 'g' for green, and 'm' for magenta.

The hold on command is used to allow multiple plots to be displayed in the same figure. The hold off command is used to turn off the hold functionality after plotting the variables.

The legend function is used to add a legend to the plot, specifying which line corresponds to which variable.

Finally, the xlabel, ylabel, and title functions are used to add labels and a title to the plot.

Note: You can customize the plot according to your specific requirements, such as line style, marker style, etc.

related categories

gistlibby LogSnag