MATLAB - Plot Vectors
MATLAB - Visualizing Vector Data
Section titled “MATLAB - Visualizing Vector Data”In MATLAB, a “vector” is a one-dimensional array, a fundamental data structure. When we talk about “plotting vectors,” we can mean two different things:
- Plotting the Data Within a Vector: This involves visualizing the sequence of values stored in the vector. Functions like
plot(),stem(), andbar()are used for this. For example, plotting a time series or a set of measurements. - Plotting Geometric Vectors as Arrows: This involves visualizing direction and magnitude at specific points in a coordinate system. This is common in physics (e.g., force fields) and mathematics (e.g., gradient fields). The primary function for this is
quiver().
This tutorial focuses on the second case: using the quiver function to create vector field plots.
The quiver Function
Section titled “The quiver Function”The quiver function draws 2D arrows to represent vectors. At its core, it requires the starting coordinates (X, Y) and the vector components (U, V) for each arrow.
Syntax
Section titled “Syntax”quiver(X, Y, U, V)quiver(U, V)quiver(___, scale)quiver(___, LineSpec)q = quiver(___)quiver(X, Y, U, V): Draws arrows at coordinates specified by corresponding elements ofXandY. The horizontal component of each arrow is given byUand the vertical component byV.quiver(U, V): IfXandYare omitted, MATLAB plots the vectors on an evenly spaced grid.quiver(___, scale): Controls the length of the arrows. Ifscaleis a positive number, it acts as a multiplier. Ifscaleis0(or'off'), it disables automatic scaling, and the arrows are drawn with lengths determined directly byUandV.quiver(___, LineSpec): A string to specify the line style, marker, and color (e.g.,'r--o'for a red, dashed line with circle markers).q = quiver(___): Returns aQuiverobject. This handle (q) is essential for modern MATLAB, as it allows you to customize the plot’s properties after creation.
Practical Examples
Section titled “Practical Examples”Example 1: Plotting a Few Individual Vectors
Section titled “Example 1: Plotting a Few Individual Vectors”This example plots three distinct vectors starting from different points.
% Define the starting points (X, Y)X = [1, 3, 4];Y = [2, 4, 1];
% Define the vector components (U, V)U = [2, -1, 0]; % Horizontal componentsV = [1, 1, -2]; % Vertical components
figure;hold on;grid on;axis equal; % Ensures correct aspect ratio
% Create the quiver plot and store the handleq = quiver(X, Y, U, V);
% Plot the starting points for clarityplot(X, Y, 'ro', 'MarkerFaceColor', 'r');
% Customize the plot using the handleq.Color = 'blue';q.LineWidth = 2;q.AutoScaleFactor = 0.9; % Adjust automatic scaling
% Add labels and titlexlabel('X-axis');ylabel('Y-axis');title('Plotting Individual Vectors');legend('Start Points', 'Vectors');hold off;Expected Output: A plot with three blue arrows originating from three red dots. The axis equal command ensures that a vector [1, 1] would appear at a 45-degree angle.
Example 2: Visualizing a Vector Field
Section titled “Example 2: Visualizing a Vector Field”A more powerful use of quiver is to visualize a vector field, such as the gradient of a function. Let’s plot the field for $$f(x,y) = x^2 + y^2$$.
% 1. Create a grid of points[X, Y] = meshgrid(-2:0.4:2, -2:0.4:2);
% 2. Define the components of the vector field.% The gradient of f(x,y) = x^2 + y^2 is ∇f = <2x, 2y>.U = 2 * X; % Horizontal componentV = 2 * Y; % Vertical component
% 3. Create the plotfigure;q = quiver(X, Y, U, V);
% 4. Customize appearanceaxis tight;xlabel('x');ylabel('y');title('Vector Field of ∇f = <2x, 2y>');q.LineWidth = 1;q.Color = [0.2 0.2 0.2]; % Dark grayExpected Output: A plot showing a grid of arrows, all pointing away from the origin (0,0), with their lengths increasing as they get farther from the center. This correctly visualizes the gradient field.
Example 3: Controlling Scale and Style
Section titled “Example 3: Controlling Scale and Style”This example shows how to disable automatic scaling to represent true vector magnitude and apply a LineSpec.
[X, Y] = meshgrid(0:2, 0:2);U = ones(3, 3);V = ones(3, 3);
figure;
% Subplot 1: Automatic scaling (default)subplot(1, 2, 1);quiver(X, Y, U, V);title('Default Auto-Scaling');axis([-1 3 -1 3]);
% Subplot 2: Scaling turned offsubplot(1, 2, 2);% The '0' turns off scaling. 'r' makes the vectors red.quiver(X, Y, U, V, 0, 'r');title('Scaling Off (True Magnitude)');axis([-1 3 -1 3]);Expected Output: Two subplots. The left plot has reasonably sized arrows that don’t overlap. The right plot has longer red arrows, as their length is now directly determined by the magnitude of the vectors (which is sqrt(1^2 + 1^2) ≈ 1.414).
Best Practices & Common Pitfalls
Section titled “Best Practices & Common Pitfalls”- Dimension Mismatch: The most common error is when the matrices
X,Y,U, andVdo not have the same size. Always double-check their dimensions before callingquiver. - Use
meshgridfor Fields: When plotting a field, always generate your coordinate grid usingmeshgridto ensureXandYare correctly formatted for vector-based calculations. - Leverage the Object Handle: For complex plots, always store the output of
quiverin a handle (q = quiver(...)). This allows for fine-grained control over dozens of properties (color, line width, head style, etc.) after the plot has been created. axis equalis Your Friend: For geometric or physics-based vector plots, useaxis equalordaspect([1 1 1])to ensure the correct spatial representation of vector angles and relative magnitudes.