Polyglot
Languages MATLAB types
MATLAB § types

Types

MATLAB’s type system is dynamic, array-oriented, and column-major. Every value is an array; a scalar is a 1×1 array. Every value has a classdouble, single, int32, logical, char, string, cell, struct, table, function_handle, or the name of a user-defined classdef class. The default numeric class is double (IEEE 754 64-bit floating-point) and the great majority of MATLAB code computes in doubles; the integer and single-precision classes exist for memory-sensitive work, hardware interaction, and code generation. The combination — arrays as primitive, doubles as default, dynamic dispatch on class — is the substance of MATLAB’s type discipline.

Fundamental classes

ClassStoredNotes
double64-bit IEEE 754 floatDefault numeric type.
single32-bit IEEE 754 floatUsed for memory-bound work and GPU code.
int8, int16, int32, int64Signed integersSaturating arithmetic by default (no overflow wrap).
uint8, uint16, uint32, uint64Unsigned integersImage data is conventionally uint8.
logical1-byte booleanResult of ==, <, &, etc.
charUTF-16 code unitsA character array; 'hello' is 1×5.
stringBoxed UTF-16 stringsSince R2016b; "hello" is a 1×1 string scalar.
cellHeterogeneous containerElements are arrays of any class.
structNamed-field recordFields are arrays of any class.
table, timetableTabular dataHeterogeneous columns with column names.
function_handleCallableBound function or anonymous function.
dictionaryKey-value mapSince R2022b.
user classdefObjectValue or handle semantics.

The class of a value is reported by class(x); type predicates have names like isnumeric, isfloat, isinteger, ischar, isstring, iscell, isstruct, islogical, isa(x, 'classname').

Size, dimensions, and the column-major layout

Every array has a size: a row vector of length at least two. A scalar is 1×1, a row vector is 1×N, a column vector is N×1, a matrix is M×N, an N-d array is M×N×P×… Storage is column-major — successive memory locations advance down the first column, then to the second column, and so on — which matches Fortran and the LAPACK conventions that MATLAB was built to call.

size(A)         % row vector of dimensions
numel(A)        % total number of elements
ndims(A)        % number of dimensions (always >= 2)
length(A)       % the largest dimension
isempty(A)      % true if any dimension is zero

A subtle consequence of the column-major layout: linear indexing A(k) visits elements down columns first.

A = [1 2 3; 4 5 6];     % 2-by-3
A(:)
% [1; 4; 2; 5; 3; 6]

Numeric promotion and the dominance of double

Arithmetic combines values by promoting the operands to a common class. The dominant class is double; mixing double with an integer yields the integer class (subject to saturation), mixing single with double yields single, and logical is treated as numeric in arithmetic. The rules differ from the usual C-family promotions in one consequential way: int32(1) + 1.5 yields int32(3) — the literal 1.5 is rounded to fit the integer class — and all integer arithmetic saturates at the class’s minimum and maximum rather than wrapping.

int8(120) + int8(50)
% ans = 127             (saturated, not -86)

int32(1) + 1.5
% ans = 3               (1.5 rounded to fit int32)

The rule is unusual and is occasionally a footgun for programmers coming from C. For wrap-around arithmetic, cast to a wider class or use intmax/intmin explicitly.

Logical class

The result of a comparison or logical operator is a logical array. true and false are functions returning scalar logical values; true(3) produces a 3×3 all-true matrix. Logical arrays index other arrays through the logical indexing convention.

x = [1 -2 3 -4 5];
x > 0
% 1×5 logical: [1 0 1 0 1]
x(x > 0)
% [1 3 5]

The functions any and all reduce a logical array along a dimension; find returns the indices of non-zero (or true) entries.

NaN and Inf

The IEEE 754 special values NaN (not a number) and Inf (infinity) are first-class. 0/0 produces NaN; 1/0 produces Inf with appropriate sign. NaN is unordered: NaN == NaN is false and the predicate isnan is the standard test. Most reduction functions have an 'omitnan' flag — sum(x, 'omitnan'), mean(x, 'omitnan') — that skips NaN values, and the convenience functions sum(x, 'omitmissing') and the dedicated nanmean-style helpers play similar roles in newer code.

[NaN NaN 1 2 3 4]
mean(ans)               % NaN
mean(ans, 'omitnan')    % 2.5

Empty arrays

An empty array has at least one zero dimension. The canonical empty value is [], which is 0×0 double. Empty arrays propagate through most operations; appending [] to an array is the idiomatic way to delete elements:

x = 1:5;
x(2) = []
% x = [1 3 4 5]
A = magic(4);
A(:, 2) = []           % delete the second column

Empty arrays of specific shape — zeros(0, 3) is 0×3 — preserve dimensionality for concatenation and are important in code that builds arrays incrementally.

char vs string

MATLAB historically represents text as a char array — a one-dimensional matrix of UTF-16 code units, written with single quotes. A 'hello' is a 1×5 char; 'hello'(1) is the 1×1 char 'h'. Two character arrays are equal element-wise only if they have the same size, which is the source of frequent surprises for programmers used to string-as-scalar.

The newer string class — written with double quotes, introduced in R2016b — boxes one or more strings into an array of scalar strings. "hello" is a 1×1 string; ["hello", "world"] is a 1×2 string. Strings support a substantial library of methods (split, replace, contains, startsWith, + for concatenation) and are now the recommended representation for textual data in new code, with char reserved for legacy and for character-oriented operations. The two are discussed at length in Strings and char arrays.

struct, cell, table

Composite types come in three flavours:

  • struct is a record with named fields. Fields are accessed with dot notation: s.name, s.age. A struct array is an array of structs with the same fields. The dynamic-field form s.(fieldName) permits programmatic field access.
  • cell is a heterogeneous container indexed with curly braces: c{1} returns the contents of the first cell; c(1) returns a 1×1 cell containing the same value. Cell arrays are the conventional way to store a vector of strings of different lengths and to pass variable-length argument lists.
  • table is a column-oriented heterogeneous tabular type (analogous to a Pandas DataFrame), with named columns of possibly different classes. The closely related timetable has a time-axis row label and is the standard container for time-series data.
s = struct('name', "Ada", 'birthYear', 1815);
c = {1, "two", [3 4 5]};
T = table([1; 2; 3], ["a"; "b"; "c"], 'VariableNames', ["id", "label"]);

function_handle

A function handle is a first-class value referring to a function. Two forms:

f = @sin;                          % named function
g = @(x) x.^2 + 1;                 % anonymous function
arrayfun(@(k) k^2, 1:5)
% [1 4 9 16 25]

Function handles are passed to higher-order functions (arrayfun, cellfun, fzero, ode45, fminunc), stored in cells, and used to capture closures over workspace variables. They are covered in Anonymous functions and handles.

Casting and the cast family

Explicit conversion uses class-named functions:

double(int32(3))         % 3 (double)
int8(127.6)              % 127 (saturated, rounded)
uint8([0.1 0.5 0.9] * 255)
% [26 128 230]
char(65)                 % 'A'
string(123)              % "123"

The general cast(x, "uint16") form takes the destination class as a string; the inverse class(x) returns it. The integer casts round to the nearest representable integer with saturation — they neither truncate nor wrap, which is the correct default for image and signal data but is occasionally surprising.

isa and the class hierarchy

Every class is either a fundamental built-in or a user-defined classdef. User classes may inherit from built-ins or from other user classes. The isa(x, 'name') predicate tests class membership with inheritance; the class(x) function returns the immediate class. The predicate metaclass(x) returns a meta.class object that describes the class — its properties, methods, and superclasses — and is the basis of MATLAB’s reflection facility.

isa(3, 'numeric')        % true
isa(3, 'double')         % true
isa(3, 'integer')        % false
class(3)                 % 'double'