Skill Tracer
Skills › Scientific Agent Skills › matlab › matrices-arrays.md

matrices-arrays.md

234 lines · skills/matlab/references/matrices-arrays.md at 5f2bc03

Open on GitHub
1# Arrays, Indexing, Data Types, and Performance
2
3This reference targets MATLAB R2026a. Verify GNU Octave behavior separately.
4

Arrays, Indexing, Data Types, and Performance

This reference targets MATLAB R2026a. Verify GNU Octave behavior separately.

Raw lines 1 to 4
5## Array model
6
7MATLAB is 1-based and column-major. Most numeric literals are `double`.
8Orientation and trailing singleton dimensions matter.
9
10```matlab
11row = 1:5; % 1-by-5
12column = (1:5).'; % 5-by-1, nonconjugate transpose
13A = reshape(1:12, 3, 4); % values fill down columns
15sameShape = zeros(size(A), "like", A);
16singleData = zeros(100, 1, "single");
17logicalMask = false(size(A));
18```
20Use `.'` for a plain transpose and `'` for a conjugate transpose. Use
21`size(A,dim)`, `numel`, and `ndims`; avoid `length` when a specific dimension
22is intended.

Array model

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.

Raw lines 5 to 23
24### Core storage choices
26| Type | Use | Caution |
27|---|---|---|
28| dense numeric/logical array | homogeneous computation | implicit conversion and memory |
29| sparse numeric/logical array | low-density 2-D matrices | not every operation preserves sparsity |
30| string array | text with missing values | differs from character arrays |
31| categorical | finite labels and ordering | undefined category is missing |
32| cell array | heterogeneous containers | `{}` versus `()` semantics |
33| structure | named heterogeneous fields | structure arrays complicate shape |
34| table | named, equal-height variables | `()` versus `{}` versus dot indexing |
35| timetable | table with row times | time zone, sorting, duplicates, alignment |
36| datetime/duration | time points/elapsed time | time zones and calendar duration differ |
38Choose integer classes for storage or exact integer semantics, not as a drop-in
39for floating computation. Integer overflow and mixed-class operations need
40explicit tests. Preserve units in names or metadata.

Core storage choices

TypeUseCaution
dense numeric/logical arrayhomogeneous computationimplicit conversion and memory
sparse numeric/logical arraylow-density 2-D matricesnot every operation preserves sparsity
string arraytext with missing valuesdiffers from character arrays
categoricalfinite labels and orderingundefined category is missing
cell arrayheterogeneous containers{} versus () semantics
structurenamed heterogeneous fieldsstructure arrays complicate shape
tablenamed, equal-height variables() versus {} versus dot indexing
timetabletable with row timestime zone, sorting, duplicates, alignment
datetime/durationtime points/elapsed timetime 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.

Raw lines 24 to 41
42## Indexing
44```matlab
45value = A(2, 3); % row 2, column 3
46linear = A(5); % column-major linear index
47row = A(2, :);
48lastRows = A(max(1,end-2):end, :);
49positive = A(A > 0);
50A(A < 0) = 0;
52[r, c] = ind2sub(size(A), linearIndex);
53linearIndex = sub2ind(size(A), r, c);
54```
56Prefer logical indexing for selection and `find` only when numeric indices are
57needed. Verify mask shape. Deleting with `A(index)=[]` changes shape and can be
58ambiguous for multidimensional arrays.
60R2026b changes an easy-to-miss edge case: linear logical deletion with an
61all-false mask can still reshape built-in arrays into a row vector. Preserve
62and check the intended shape even when no values match, and include a
63no-match case in migration tests.

Indexing

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.

R2026b changes an easy-to-miss edge case: linear logical deletion with an all-false mask can still reshape built-in arrays into a row vector. Preserve and check the intended shape even when no values match, and include a no-match case in migration tests.

Raw lines 42 to 64
65### Cell, structure, and table indexing
67```matlab
68C = {42, "sample"; [1 2], datetime("today")};
69cellContainer = C(1, :); % still a cell array
70cellContent = C{1, 1}; % contained value
72S.SampleID = "S01";
73name = S.("SampleID");
75tableSlice = T(1:10, ["Time" "Value"]); % table
76numericValues = T{:, "Value"}; % underlying content
77oneVariable = T.Value; % variable content
78```
80Curly extraction from a table succeeds only when selected variable contents
81can concatenate. Preserve table form when variable names and metadata matter.

Cell, structure, and table indexing

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.

Raw lines 65 to 82
83## Operators and implicit expansion
85| Operation | Matrix | Element-wise |
86|---|---|---|
87| multiply | `A*B` | `A.*B` |
88| divide | `A/B`, `A\B` | `A./B`, `A.\B` |
89| power | `A^n` | `A.^n` |
91Addition, subtraction, comparisons, and many element-wise functions use
92compatible-size implicit expansion. Since R2016b, a column and row can create
93an outer result:
95```matlab
96x = (1:3).';
97y = 10:10:40;
98outerSum = x + y; % 3-by-4
99```
101Before relying on expansion, assert intended orientation:
103```matlab
104assert(iscolumn(x));
105assert(isrow(y));
106```
108Do not use `repmat` solely to emulate supported implicit expansion, but use it
109when an explicitly materialized tiled array is actually needed.

Operators and implicit expansion

OperationMatrixElement-wise
multiplyA*BA.*B
divideA/B, A\BA./B, A.\B
powerA^nA.^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.

Raw lines 83 to 110
111## Missing and nonfinite values
113Standard missing values are type-specific:
115- `NaN`: `double`, `single`, `duration`, `calendarDuration`
116- `NaT`: `datetime`
117- `<missing>`: `string`
118- `<undefined>`: `categorical`
119- `''` inside a cell array of character vectors
121Integer and logical arrays have no standard missing value. A sentinel such as
122`-99` is a data contract, not a MATLAB default.
124```matlab
125missingMask = ismissing(T);
126anyMissing = anymissing(T);
127clean = rmmissing(T);
128filled = fillmissing(T, "linear", DataVariables="Value");
129```
131Define whether `Inf` is valid separately; it is not a standard missing
132floating-point value. `isfinite` distinguishes finite values. `ismissing`
133ignores timetable row times, so validate row times explicitly.

Missing and nonfinite values

Standard missing values are type-specific:

  • NaN: double, single, duration, calendarDuration
  • NaT: datetime
  • <missing>: string
  • <undefined>: categorical
  • '' inside a cell array of character vectors

Integer 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.

Raw lines 111 to 134
135## Tables and timetables
137Every table variable has the same row count but can have a different type and
138width. Timetables add row times.
140```matlab
141T = table(sampleID, group, value, ...
142 VariableNames=["SampleID" "Group" "Value"]);
144TT = timetable(time, value, quality, ...
145 VariableNames=["Value" "Quality"]);
146TT = sortrows(TT);
147hourly = retime(TT, "hourly", "mean");
148aligned = synchronize(TT1, TT2, "intersection");
149```
151Before time alignment:
1531. normalize or record time zones;
1542. define duplicate-time policy;
1553. sort row times;
1564. choose union/intersection and interpolation/aggregation deliberately;
1575. record daylight-saving and calendar assumptions.
159Direct calculations on tables/timetables are supported for compatible
160variables, but mixed nonnumeric variables can invalidate an operation.
161Selecting numeric variables first is often clearer:
163```matlab
164numericT = T(:, vartype("numeric"));
165```

Tables and timetables

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:

  1. normalize or record time zones;
  2. define duplicate-time policy;
  3. sort row times;
  4. choose union/intersection and interpolation/aggregation deliberately;
  5. record daylight-saving and calendar assumptions.

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"));
Raw lines 135 to 166
167## Concatenation and reshaping
169```matlab
170wide = [A B];
171tall = [A; B];
172flat = A(:);
173B = reshape(A, [], 4);
174C = permute(X, [2 1 3]);
175```
177Concatenated dimensions and classes must be compatible. `squeeze` can remove
178different dimensions depending on input shape; avoid it in APIs whose output
179rank must be stable.

Concatenation and reshaping

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.

Raw lines 167 to 180
181## Performance without folklore
1831. Write the clearest correct array code.
1842. Use representative data and `timeit`; use the profiler for call-level
185 diagnosis.
1863. Preallocate when a loop's output shape is known.
1874. Vectorize operations that map naturally to array kernels.
1885. Keep a loop when vectorization creates large temporaries or obscures logic.
1896. Preserve sparsity and data class where appropriate.
1907. Benchmark each supported release/platform; R2026a includes implementation
191 speedups that can change old trade-offs.
193```matlab
194y = zeros(size(x), "like", x);
195for k = 1:numel(x)
196 y(k) = localTransform(x(k));
197end
198```
200Avoid growing arrays in a loop. However, do not preallocate the wrong class or
201shape. `zeros(size(x),"like",x)` is usually safer than an unqualified `zeros`.
203Parallel arrays, GPU arrays, tall arrays, `parfor`, and distributed arrays
204require specific products and supported functions. They also change ordering,
205reduction, RNG, and tolerance concerns. Do not suggest them merely because a
206loop exists.

Performance without folklore

  1. Write the clearest correct array code.
  2. Use representative data and timeit; use the profiler for call-level diagnosis.
  3. Preallocate when a loop's output shape is known.
  4. Vectorize operations that map naturally to array kernels.
  5. Keep a loop when vectorization creates large temporaries or obscures logic.
  6. Preserve sparsity and data class where appropriate.
  7. Benchmark each supported release/platform; R2026a includes implementation speedups that can change old trade-offs.
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.

Raw lines 181 to 207
208## Numerical review checklist
210- [ ] Shapes and orientation are asserted where expansion matters.
211- [ ] Matrix versus element-wise operators are intentional.
212- [ ] Conjugation behavior is intentional.
213- [ ] Indexing preserves expected rank and container type.
214- [ ] Missing, nonfinite, and sentinel policies are explicit.
215- [ ] Table variable names/types and timetable time zones are preserved.
216- [ ] Integer overflow and mixed-class conversion are tested.
217- [ ] Sparse inputs remain sparse where required.
218- [ ] Preallocation and vectorization are measured, not assumed.
219- [ ] Memory estimates include temporaries and expanded outputs.

Numerical review checklist

  • [ ] Shapes and orientation are asserted where expansion matters.
  • [ ] Matrix versus element-wise operators are intentional.
  • [ ] Conjugation behavior is intentional.
  • [ ] Indexing preserves expected rank and container type.
  • [ ] Missing, nonfinite, and sentinel policies are explicit.
  • [ ] Table variable names/types and timetable time zones are preserved.
  • [ ] Integer overflow and mixed-class conversion are tested.
  • [ ] Sparse inputs remain sparse where required.
  • [ ] Preallocation and vectorization are measured, not assumed.
  • [ ] Memory estimates include temporaries and expanded outputs.
Raw lines 208 to 220
221## Sources (reviewed 2026-10-01)
223- [Array Indexing](https://www.mathworks.com/help/matlab/math/array-indexing.html)
224- [Compatible Array Sizes for Basic Operations](https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html)
225- [MATLAB Data Types](https://www.mathworks.com/help/matlab/data-types.html)
226- [Tables](https://www.mathworks.com/help/matlab/tables.html)
227- [Timetables](https://www.mathworks.com/help/matlab/timetables.html)
228- [`ismissing`](https://www.mathworks.com/help/matlab/ref/ismissing.html)
229- [Missing Data in MATLAB](https://www.mathworks.com/help/matlab/data_analysis/missing-data-in-matlab.html)
230- [Vectorization](https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html)
231- [Preallocation](https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html)
232- [`timeit`](https://www.mathworks.com/help/matlab/ref/timeit.html)
233- [Profile MATLAB Code](https://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html)
234- [R2026b release notes: logical deletion](https://www.mathworks.com/help/matlab/release-notes.html)

Sources (reviewed 2026-10-01)

Raw lines 221 to 234