plot two graphs in same figure in matlab

You can plot two graphs in the same figure using the subplot function in Matlab. The subplot function allows you to divide the figure into multiple smaller subplots, where you can plot your graphs. You can also use the hold function to prevent the previous plot from being cleared when you plot a new graph on the same figure. Here is an example code snippet:

main.m
% create some data
x = linspace(0, 2*pi, 100);
y1 = sin(x);
y2 = cos(x);

% create a new figure
figure;

% plot the first graph in the first subplot
subplot(2,1,1);
plot(x, y1);
title('sin(x)');

% plot the second graph in the second subplot
subplot(2,1,2);
plot(x, y2);
title('cos(x)');

% use the 'hold on' command to prevent previous plot from being cleared
hold on;

% plot a new line on the same graph
plot(x, y1.*y2, 'r');
legend('sin(x)', 'cos(x)', 'sin(x)*cos(x)');
474 chars
25 lines

In this example, we create two subplots, one on top of the other, using the subplot function. We plot the sin(x) function in the first subplot, and the cos(x) function in the second subplot using the plot function. Then, we use the hold on command to prevent the previous plot from being cleared when we plot a new line on the same graph using the plot function. Finally, we add a legend to the graph using the legend function.

related categories

gistlibby LogSnag