getfield — Access struct or object fields in MATLAB and RunMat.
value = getfield(S, field) returns the contents of S.field. Nested field access, struct-array indexing forms, and object property access follow MATLAB semantics.
Syntax
value = getfield(S, field)
value = getfield(S, field_or_index, ...)
value = getfield(S, {idx0}, field_or_index, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
S | Any | Yes | — | Struct, struct array, object, or supported metadata container. |
field | PropertyName | Yes | — | Field/property name. |
path | Any | Variadic | — | Alternating field names and optional index-selector cells `{...}` for nested access. |
S | Any | Yes | — | Struct array or supported indexable container. |
index_selector | Any | Yes | — | Leading index selector in a cell array, e.g. `{2}` or `{end}`. |
Returns
| Name | Type | Description |
|---|---|---|
value | Any | Selected field/property value. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:getfield:NotEnoughInputs | No field-name/path arguments are supplied. | getfield: expected at least one field name |
RunMat:getfield:FieldExpected | Field name is missing after indices or argument parsing. | getfield: expected field name arguments |
RunMat:getfield:IndexSelectorType | Index selector is not provided as a cell array. | getfield: indices must be provided in a cell array |
RunMat:getfield:InvalidIndex | Index components are malformed, empty, unsupported, or not positive integers. | getfield: invalid index element |
RunMat:getfield:FieldNameType | Field name is not a string scalar or 1-by-N char vector. | getfield: expected field name |
RunMat:getfield:IndexShape | Indexing rank/shape is unsupported for the targeted value. | getfield: unsupported index shape for target value |
RunMat:getfield:NonStructReference | Field lookup is attempted on a non-struct/non-object container. | Struct contents reference from a non-struct array object. |
RunMat:getfield:IndexOutOfBounds | Resolved index is outside the bounds of the targeted value. | Index exceeds the number of array elements. |
RunMat:getfield:MissingField | Requested field does not exist on struct/exception/listener. | Reference to non-existent field |
RunMat:PropertyPrivateAccess | Property exists but is private/inaccessible from this context. | You cannot get this property from the current context. |
RunMat:getfield:ObjectProperty | Object property access is invalid (static-through-instance, unknown, or non-public). | getfield: invalid object property access |
RunMat:getfield:InvalidHandle | Handle object is invalid/deleted. | Invalid or deleted handle object |
RunMat:getfield:InternalError | Internal value conversion or output assembly failed. | getfield: internal error |
How getfield works
- Field names must be character vectors or string scalars. Several field names in a row navigate nested structs:
getfield(S, "outer", "inner")is equivalent toS.outer.inner. - When
Sis a struct array,getfield(S, "field")examines the first element by default. Provide indices in a cell array to target another element:getfield(S, {k}, "field")yieldsS(k).field. - After a field name you may supply an index cell to subscript the field value, e.g.
getfield(S, "values", {row, col}). Each position accepts positive integers or the keywordendto reference the last element in that dimension. - MATLAB-style objects honour property attributes: static or private properties raise errors, while dependent properties invoke
get.<name>when available. - Handle objects dereference to their underlying instance automatically. Deleted handles raise the standard MATLAB-style error.
MExceptionvalues expose themessage,identifier, andstackfields for compatibility with MATLAB error handling.
Does RunMat run getfield on the GPU?
getfield is metadata-only. When structs or objects contain GPU tensors, the tensors remain on the device. The builtin manipulates only the host-side metadata and does not dispatch GPU kernels or gather buffers back to the CPU. Results inherit residency from the values being returned.
GPU memory and residency
You do not have to move data between CPU and GPU explicitly when calling getfield. The builtin works entirely with metadata and returns handles or tensors in whatever memory space they already inhabit.
Examples
Reading a scalar struct field
stats = struct("mean", 42, "stdev", 3.5);
mu = getfield(stats, "mean")Expected output:
mu = 42Navigating nested structs with multiple field names
cfg = struct("solver", struct("name", "cg", "tolerance", 1e-6));
tol = getfield(cfg, "solver", "tolerance")Expected output:
tol = 1.0000e-06Accessing an element of a struct array
people = struct("name", {"Ada", "Grace"}, "id", {101, 102});
lastId = getfield(people, {2}, "id")Expected output:
lastId = 102Reading the first element of a struct array automatically
people = struct("name", {"Ada", "Grace"}, "id", {101, 102});
firstName = getfield(people, "name")Expected output:
firstName = "Ada"Using end to reference the last item in a field
series = struct("values", {1:5});
lastValue = getfield(series, "values", {"end"})Expected output:
lastValue = 5Indexing into a numeric field value
measurements = struct("values", {[1 2 3; 4 5 6]});
entry = getfield(measurements, "values", {2, 3})Expected output:
entry = 6Gathering the exception message from a try/catch block
try
error("RunMat:domainError", "Bad input");
catch e
msg = getfield(e, "message");
endExpected output:
msg = 'Bad input'Using getfield with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how getfield changes the result.
Run a small getfield example, explain the result, then change one input and compare the output.
FAQ
Does getfield work on non-struct values?⌄
No. The first argument must be a scalar struct, a struct array (possibly empty), an object instance created with new_object, a handle object, or an MException. Passing other types raises an error.
How do I access nested struct fields?⌄
Provide every level explicitly: getfield(S, "parent", "child", "leaf") traverses the same path as S.parent.child.leaf.
How do I read from a struct array?⌄
Supply a cell array of indices before the first field name. For example, getfield(S, {3}, "value") mirrors S(3).value. Indices are one-based like MATLAB.
Can I index the value stored in a field?⌄
Yes. You may supply scalars or end inside the index cell to reference elements of the field value.
Do dependent properties run their getter methods?⌄
Yes. If a property is marked Dependent and a get.propertyName builtin exists, getfield invokes it. Otherwise the backing field <property>_backing is inspected.
What happens when I query a deleted handle object?⌄
RunMat mirrors MATLAB by raising Invalid or deleted handle object 'ClassName'.
Related Structs functions
fieldnames · isfield · orderfields · rmfield · setfield · struct
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how getfield is executed, line by line, in Rust.
- View the source for getfield in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.