Skip to content

MATLAB - Commands

MATLAB provides a powerful interactive environment for numerical computation, data analysis, and visualization. You can execute commands directly in the Command Window at the >> prompt. This tutorial covers essential commands for a modern MATLAB workflow.

We will explore commands for managing your session, interacting with the file system, handling I/O, and working with MATLAB’s core data structures.

These commands help you manage the variables in your workspace and control your MATLAB session. The Workspace browser in the MATLAB Desktop provides a graphical interface for these operations.

CommandPurpose
clcClears the Command Window text, keeping the workspace intact.
clearRemoves all variables from the current workspace. Use clear varName to remove a specific variable.
existChecks for the existence of a variable, file, or folder. E.g., exist('myVar', 'var').
globalDeclares variables to be global, accessible across different functions. Best Practice: Use with caution; passing variables as function arguments is generally preferred.
helpDisplays help text for a function in the Command Window. E.g., help plot.
docOpens the full documentation page for a function, which is often more detailed than help. E.g., doc plot.
lookforSearches the first line of help text for a keyword. Useful when you don’t know the exact function name.
quitStops MATLAB.
whoLists the names of variables in the current workspace.
whosLists current variables with details like size, bytes, and class.

Modern data science requires robust tools for importing and exporting data. MATLAB excels at handling various file formats, from simple text files to large datasets.

CommandPurpose
cdChanges the current directory. Use cd .. to go up one level.
dirLists the contents of the current directory.
pwdDisplays the current working directory path.
load / saveLoads and saves workspace variables to a MATLAB-specific .mat file. E.g., save('mySession.mat').
readtableModern Best Practice. Reads tabular data from files like .csv or .xlsx into a table data type.
writetableModern Best Practice. Writes a table to a file like .csv or .xlsx.
readmatrix / writematrixReads/writes purely numeric data from/to text or spreadsheet files.
deleteDeletes a file. Use with caution.
typeDisplays the contents of a text-based file (e.g., a .m script).
diaryCreates a log of commands and output from your MATLAB session.
wklreadDeprecated. This function was used for older Lotus 1-2-3 spreadsheets. Use readtable or readmatrix for modern spreadsheet files.

These commands control how information is displayed in the Command Window and how user input is received.

CommandPurpose
dispDisplays the contents of an array or string without printing the variable name. Useful for showing messages.
fprintfWrites formatted data to the screen or a file, offering fine-grained control over the output. Similar to C’s printf.
inputDisplays a prompt and waits for the user to enter a value.
formatControls the numeric display format in the Command Window (e.g., format long, format short, format bank).
; (semicolon)Suppresses the output of a command. Essential for preventing large matrices from flooding the screen.

MATLAB’s core strength is its handling of arrays and matrices. The following commands are fundamental for data manipulation.

CommandPurpose
sizeReturns the dimensions of an array.
lengthReturns the length of the largest array dimension. For a vector, it’s the number of elements.
numelReturns the total number of elements in an array.
reshapeChanges the size and shape of an array while preserving the number of elements.
zeros, ones, eyeCreates arrays of all zeros, all ones, or an identity matrix, respectively.
linspace, logspaceCreates linearly or logarithmically spaced vectors.
max, min, sum, prodComputes the maximum, minimum, sum, or product of array elements.
sortSorts array elements in ascending order.
findFinds indices and values of nonzero elements, or elements that satisfy a logical condition.
det, inv, rankComputes the determinant, inverse, and rank of a matrix.
cross, dotComputes vector cross products and dot products.
tableModern Data Structure. Creates a table, which can hold columns of different data types (numeric, text, categorical).
cellCreates a cell array, which can hold different types and sizes of data in each element.

MATLAB offers a powerful and flexible graphics system. The modern approach involves creating plot objects and modifying their properties for full control over visualization.

CommandPurpose
plotCreates a 2D line plot. Returns a plot object for further customization. E.g., p = plot(x, y); p.LineWidth = 2;.
scatterCreates a 2D scatter plot with markers.
barCreates a bar chart.
histogramCreates a histogram to visualize data distribution.
heatmapCreates a heatmap from a matrix.
xlabel, ylabel, title, legendAdds labels, a title, and a legend to the current axes.
figureCreates a new figure window.
tiledlayoutModern Best Practice. Creates and arranges a grid of plots within a figure. Preferred over subplot.
subplotCreates subplots in a grid. tiledlayout is recommended for newer code.
hold on / hold offAllows multiple plots to be drawn on the same axes without overwriting.
axisSets or gets the axis limits. E.g., axis([xmin xmax ymin ymax]).
grid on / grid offToggles the visibility of grid lines.
exportgraphicsModern Best Practice. Saves a figure or axes to a file (e.g., PNG, PDF, EPS). Preferred over print.