How to Use Figure in MATLAB: Syntax and Examples
In MATLAB, use the
figure function to create a new figure window or select an existing one for plotting. You can customize the figure by specifying properties like size and name using figure('PropertyName', PropertyValue).Syntax
The basic syntax of the figure function is:
figure: Creates a new figure window.figure(n): Selects or creates figure window with numbern.figure('PropertyName', PropertyValue, ...): Creates a figure with specified properties like'Name','NumberTitle','Position'.
matlab
figure figure(2) figure('Name', 'My Plot', 'NumberTitle', 'off', 'Position', [100 100 600 400])
Example
This example creates two figure windows. The first shows a sine wave, and the second shows a cosine wave with a custom title and size.
matlab
x = linspace(0, 2*pi, 100); y = sin(x); z = cos(x); figure(1) plot(x, y) title('Sine Wave') figure('Name', 'Cosine Wave', 'NumberTitle', 'off', 'Position', [200 200 500 300]) plot(x, z) title('Cosine Wave')
Output
Two figure windows open: one titled 'Figure 1' showing a sine wave, and another titled 'Cosine Wave' showing a cosine wave with custom size.
Common Pitfalls
Common mistakes when using figure include:
- Not specifying figure number and unintentionally overwriting existing figures.
- Forgetting to use
figurebefore plotting, which plots on the current figure. - Using incorrect property names or values, causing errors.
Always check if the figure exists or create a new one explicitly.
matlab
plot(x, y) % Plots on current figure, may overwrite
% Correct way:
figure(1)
plot(x, y)Quick Reference
| Usage | Description |
|---|---|
| figure | Create a new figure window |
| figure(n) | Select or create figure window number n |
| figure('Name', name) | Set figure window title |
| figure('NumberTitle', 'off') | Hide default figure number in title |
| figure('Position', [x y width height]) | Set figure window size and position |
Key Takeaways
Use
figure to create or select figure windows for plotting.Specify figure number to avoid overwriting existing figures.
Customize figure properties like title and size using name-value pairs.
Always call
figure before plotting to control where plots appear.