skills/matlab/references/matrices-arrays.md
This reference targets MATLAB R2026a. Verify GNU Octave behavior separately.
MATLAB is 1-based and column-major. Most numeric literals are double.
Orientation and trailing singleton dimensions matter.
row = 1:5; % 1-by-5
column = (1:5).'; % 5-by-1, nonconjugate transpose
A = reshape(1:12, 3, 4); % values fill down columns
sameShape = zeros(size(A), "like", A);
singleData = zeros(100, 1, "single");
logicalMask = false(size(A));
Use .' for a plain transpose and ' for a conjugate transpose. Use
size(A,dim), numel, and ndims; avoid length when a specific dimension
is intended.
| Type | Use | Caution |
|---|---|---|
| dense numeric/logical array | homogeneous computation | implicit conversion and memory |
| sparse numeric/logical array | low-density 2-D matrices | not every operation preserves sparsity |
| string array | text with missing values | differs from character arrays |
| categorical | finite labels and ordering | undefined category is missing |
| cell array | heterogeneous containers | {} versus () semantics |
| structure | named heterogeneous fields | structure arrays complicate shape |
| table | named, equal-height variables | () versus {} versus dot indexing |
| timetable | table with row times | time zone, sorting, duplicates, alignment |
| datetime/duration | time points/elapsed time | time zones and calendar duration differ |
Choose integer classes for storage or exact integer semantics, not as a drop-in for floating computation. Integer overflow and mixed-class operations need explicit tests. Preserve units in names or metadata.
value = A(2, 3); % row 2, column 3
linear = A(5); % column-major linear index
row = A(2, :);
lastRows = A(max(1,end-2):end, :);
positive = A(A > 0);
A(A < 0) = 0;
[r, c] = ind2sub(size(A), linearIndex);
linearIndex = sub2ind(size(A), r, c);
Prefer logical indexing for selection and find only when numeric indices are
needed. Verify mask shape. Deleting with A(index)=[] changes shape and can be
ambiguous for multidimensional arrays.
C = {42, "sample"; [1 2], datetime("today")};
cellContainer = C(1, :); % still a cell array
cellContent = C{1, 1}; % contained value
S.SampleID = "S01";
name = S.("SampleID");
tableSlice = T(1:10, ["Time" "Value"]); % table
numericValues = T{:, "Value"}; % underlying content
oneVariable = T.Value; % variable content
Curly extraction from a table succeeds only when selected variable contents can concatenate. Preserve table form when variable names and metadata matter.
| Operation | Matrix | Element-wise |
|---|---|---|
| multiply | A*B | A.*B |
| divide | A/B, A\B | A./B, A.\B |
| power | A^n | A.^n |
Addition, subtraction, comparisons, and many element-wise functions use compatible-size implicit expansion. Since R2016b, a column and row can create an outer result:
x = (1:3).';
y = 10:10:40;
outerSum = x + y; % 3-by-4
Before relying on expansion, assert intended orientation:
assert(iscolumn(x));
assert(isrow(y));
Do not use repmat solely to emulate supported implicit expansion, but use it
when an explicitly materialized tiled array is actually needed.
Standard missing values are type-specific:
NaN: double, single, duration, calendarDurationNaT: datetime<missing>: string<undefined>: categorical'' inside a cell array of character vectorsInteger and logical arrays have no standard missing value. A sentinel such as
-99 is a data contract, not a MATLAB default.
missingMask = ismissing(T);
anyMissing = anymissing(T);
clean = rmmissing(T);
filled = fillmissing(T, "linear", DataVariables="Value");
Define whether Inf is valid separately; it is not a standard missing
floating-point value. isfinite distinguishes finite values. ismissing
ignores timetable row times, so validate row times explicitly.
Every table variable has the same row count but can have a different type and width. Timetables add row times.
T = table(sampleID, group, value, ...
VariableNames=["SampleID" "Group" "Value"]);
TT = timetable(time, value, quality, ...
VariableNames=["Value" "Quality"]);
TT = sortrows(TT);
hourly = retime(TT, "hourly", "mean");
aligned = synchronize(TT1, TT2, "intersection");
Before time alignment:
Direct calculations on tables/timetables are supported for compatible variables, but mixed nonnumeric variables can invalidate an operation. Selecting numeric variables first is often clearer:
numericT = T(:, vartype("numeric"));
wide = [A B];
tall = [A; B];
flat = A(:);
B = reshape(A, [], 4);
C = permute(X, [2 1 3]);
Concatenated dimensions and classes must be compatible. squeeze can remove
different dimensions depending on input shape; avoid it in APIs whose output
rank must be stable.
timeit; use the profiler for call-level
diagnosis.y = zeros(size(x), "like", x);
for k = 1:numel(x)
y(k) = localTransform(x(k));
end
Avoid growing arrays in a loop. However, do not preallocate the wrong class or
shape. zeros(size(x),"like",x) is usually safer than an unqualified zeros.
Parallel arrays, GPU arrays, tall arrays, parfor, and distributed arrays
require specific products and supported functions. They also change ordering,
reduction, RNG, and tolerance concerns. Do not suggest them merely because a
loop exists.