askvity

How to plot a graph in MATLAB?

Published in MATLAB Plotting 3 mins read

Plotting a graph in MATLAB involves defining your data and then using the plot function to visualize it. Here's a breakdown of the process, based on the reference provided:

Steps to Plot a Graph in MATLAB

Here are the steps, including details on how to achieve each step:

  1. Step 1: Define the x-axis values

    You need to specify the range of values for the x-variable. This defines the horizontal axis of your graph. You can do this using MATLAB’s colon operator or the linspace function.

    • Colon Operator: For evenly spaced values, e.g., x = 0:0.1:10; (This creates a vector from 0 to 10 with increments of 0.1.)
    • linspace Function: For a specific number of evenly spaced points, e.g., x = linspace(0, 10, 100); (This creates 100 points between 0 and 10.)
  2. Step 2: Define the Function

    Declare the function you want to plot, `y = f(x)`. Use the "=" operator to define your function based on the x-values defined in the previous step. The function must have a corresponding y-value for each x-value. Here's how you define a function.

    • Example 1: Simple linear function: y = 2*x + 1;
    • Example 2: Quadratic function: y = x.^2; (The dot before the ^ is crucial for element-wise operation on the vector x.)
    • Example 3: Sine function: y = sin(x);
  3. Step 3: Use the plot Function

    Use the plot function to generate the graph. The basic syntax is plot(x, y);, where 'x' and 'y' are the vectors defined in the previous steps.

    Here's how you use the plot function:

    • Basic Plot: plot(x, y); This will create a basic line plot.
    • Adding Labels:
      • xlabel('X-axis Label'); Adds a label to the X-axis.
      • ylabel('Y-axis Label'); Adds a label to the Y-axis.
      • title('Graph Title'); Adds a title to the graph.
    • Customizing plot:
      • plot(x, y, 'r--'); This plots a red dashed line.
      • Other markers are: 'o' circle, '*' asterisk, 'x' cross, etc.

Example

Here's a complete example to create a graph of y = x^2 for x values ranging from -5 to 5 using 100 points.

% Step 1: Define x-values
x = linspace(-5, 5, 100);

% Step 2: Define the function
y = x.^2;

% Step 3: Generate the plot
plot(x, y);
xlabel('x');
ylabel('y = x^2');
title('Graph of y = x^2');
grid on; % adds a grid to the graph

This code will generate a graph of a parabola, with the x-axis spanning from -5 to 5, and the y-axis showing the squared values of x.

By following these steps, you can easily create a wide variety of graphs in MATLAB, tailored to your specific data and visualization needs.

Related Articles