MATLAB Variables

Variables contain statically-typed data.


Description

All data types in MATLAB are arrays.

Variables are names that represent a data value.

Declaration

Variables are declared using the equals sign (=). To suppress printing of the value assigned, complete the declaration with a semicolon (;).

>> m=3*5

m =

    15
>> m=3*5;

Variable names must start with a letter and must contain only letters, numbers, and underscores (_). Variable names are case-sensitive.

If an interactive command tries to declare a variable with an invalid name, the prompt is re-filled where the name is replaced with a suggested 'fix'.

To declare a variable with more than 1 element, try:

r=[3 5]

This is a row vector. To instead declare a column vector, try:

c=[3; 5]

To declare a matrix, mix the two syntaxes:

M=[1 2; 3 4]

Concatenation

To concatenate arrays horizontally, try:

A=[c M]

To concatenate arrays vertically, try:

B=[r; M]

Accessing elements

Elements of an array are accessed by indexing; note that arrays index from 1.

first = A(1)
last = A(end)
middle = A(2:end-1)

Note that 2:end-1 expands to the row vector [2 3 ... end-2 end-1]. In other words, any row vector can be used as an index, and the elements of an indexing row vector do not need to be sequential.

Assignment to elements works as expected.

A(2) = 1
A(1) = A(2)

Matrices work in the same way but are indexed by row then column.

a = A(1,2)

If only one index is provided to a matrix, it is treated as a flattened vector by stacking all columns.

Rows and columns can be accessed from a matrix like:

row = A(1,:)
column = A(:,1)

Lastly, logicals of the same size can be used to index.

B = A(A < 4)
B(B==1) = 0

Unpacking

An array can be unpacked by assigning to multiple variables, like:

[rows, cols] = size(A)


Workspace

Variables exist in a workspace. To clear the workspace, try clear.

To save all variables in the workspace to a file named like foo.mat, try save foo. To save a subset of variables instead, try save foo VARLIST.

To load a workspace from a file, try load foo. To load a subset of variables contained in that file, try load foo VARLIST.


CategoryRicottone

MATLAB/Variables (last edited 2026-01-19 15:48:57 by DominicRicottone)