multiple graphs linspace in matlab

To plot multiple graphs using linspace in matlab, we can create a for loop to generate the plot for each set of data. We can use linspace to generate the x-axis values for each plot. Here's an example code:

main.m
% Define the x-axis range
xStart = 0;
xEnd = 10;
nPoints = 100;

% Generate the x-axis values
xValues = linspace(xStart, xEnd, nPoints);

% Define the different sets of data to plot
y1 = sin(xValues);
y2 = cos(xValues);
y3 = tan(xValues);

% Create a figure
figure;

% Loop through the different sets of data and plot them
for idx = 1:length(y1)
    plot(xValues, [y1(idx), y2(idx), y3(idx)]);
    hold on;
end

% Add labels and legend
xlabel('x');
ylabel('y');
legend('sin(x)', 'cos(x)', 'tan(x)');
500 chars
27 lines

In this example, we generate the x-axis values using linspace. We then define the y-values for each set of data. We then create a for loop to loop through each set of data and plot them. The hold on command is used to keep the previous plot on the figure while adding a new one. Finally, we add the labels and legend.

Alternatively, we can use vectorization to plot multiple graphs using linspace in matlab as follows:

main.m
% Define the x-axis range
xStart = 0;
xEnd = 10;
nPoints = 100;

% Generate the x-axis values
xValues = linspace(xStart, xEnd, nPoints);

% Define the different sets of data to plot
y1 = sin(xValues);
y2 = cos(xValues);
y3 = tan(xValues);

% Create a figure
figure;

% Plot all the data at once using vectorization
plot(xValues, [y1; y2; y3]);

% Add labels and legend
xlabel('x');
ylabel('y');
legend('sin(x)', 'cos(x)', 'tan(x)');
433 chars
24 lines

In this alternate method, we still generate the x-axis values using linspace, then define the y-values for each set of data. We then plot all the data at once using vectorization, by passing in a matrix of y-values with each row representing a different set of data. Finally, we add the labels and legend as before.

gistlibby LogSnag