setfield — Assign values into struct fields, nested fields, or struct-array elements with MATLAB-compatible path syntax.
S = setfield(S, field, value) returns a copy of S with the requested field assignment applied. Additional field names and cell-based index selectors support MATLAB-compatible updates of nested structs and struct-array elements.
Syntax
S = setfield(S, field, value)
S = setfield(S, field_or_index, ..., value)
S = setfield(S, {idx0}, field_or_index, ..., value)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
S | Any | Yes | — | Input struct/object/struct-array target. |
field | PropertyName | Yes | — | Field/property name to assign. |
value | Any | Yes | — | Assigned value. |
path | Any | Variadic | — | Alternating field names and optional index-selector cells `{...}` for nested assignment. |
S | Any | Yes | — | Input struct-array target. |
index_selector | Any | Yes | — | Leading index selector in a cell array, e.g. `{2}` or `{end}`. |
Returns
| Name | Type | Description |
|---|---|---|
S | Any | Updated struct/object/array value. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:setfield:NotEnoughInputs | Input does not provide at least one path component plus assigned value. | setfield: expected at least one field name and a value |
RunMat:setfield:FieldExpected | Field/path arguments are missing after parsing selectors. | setfield: expected field name arguments |
RunMat:setfield:IndexSelectorType | Index selector is not provided as a cell array. | setfield: indices must be provided in a cell array |
RunMat:setfield:InvalidIndex | Index component is malformed, empty, unsupported, or not a positive integer. | setfield: invalid index element |
RunMat:setfield:FieldNameType | Field name is not a scalar string or 1-by-N char vector. | setfield: expected field name |
RunMat:setfield:IndexShape | Indexing rank/shape is unsupported for the targeted value. | setfield: unsupported index shape for target value |
RunMat:setfield:NonStructAssignment | Assignment target does not support struct-like field updates. | Struct contents assignment to a non-struct object is not supported. |
RunMat:setfield:IndexOutOfBounds | Resolved index is outside bounds for target value. | Index exceeds the number of array elements. |
RunMat:setfield:MissingField | Indexed assignment path references a missing field. | Reference to non-existent field |
RunMat:PropertyPrivateAccess | Property exists but get/set access is private. | setfield: private property access denied |
RunMat:PropertyStaticAccess | Property exists but is static and cannot be assigned through an instance. | setfield: static property access denied |
RunMat:setfield:ObjectProperty | Object property operation is invalid (static, non-public, or malformed setter result). | setfield: invalid object property operation |
RunMat:setfield:InvalidHandle | Handle target is invalid/deleted/null. | setfield: invalid or deleted handle object |
RunMat:setfield:InternalError | Internal conversion/allocation failed while assigning values. | setfield: internal error |
How setfield works
- Field names must be character vectors or string scalars. Provide as many field names as needed; each additional name drills deeper into nested structs, so
setfield(S,"outer","inner",value)mirrorsS.outer.inner = value. - Missing struct fields are created automatically. If intermediary structs do not exist, RunMat allocates them so that the assignment completes successfully.
- Struct arrays require a leading cell array of one-based indices, e.g.
setfield(S,{2},"field",value)orsetfield(S,{1,3},"field",value), and accept the keywordend. - You can index into a field's contents before traversing deeper by placing a cell array of indices immediately after the field name:
setfield(S,"values",{1,2},"leaf",x)matchesS.values{1,2}.leaf = x. - MATLAB-style objects honour property metadata: private setters raise access errors, static properties cannot be written through instances, and dependent properties forward to
set.<name>methods when available. - The function returns the updated struct or object. For value types the result is a new copy; handle objects still point at the same instance, and the handle is returned for chaining.
Does RunMat run setfield on the GPU?
setfield executes entirely on the host. When fields contain GPU-resident tensors, RunMat gathers those tensors to host memory before mutating them and stores the resulting host tensor back into the struct or object. No GPU kernels are launched for these assignments.
GPU memory and residency
You do not have to move data explicitly when assigning into structs. If a field contains a GPU tensor, setfield gathers it to host memory so the mutation can be performed safely. Subsequent operations decide whether to migrate it back to the GPU.
Examples
Assigning a new field in a scalar struct
s = struct();
s = setfield(s, "answer", 42);
disp(s.answer)Expected output:
42Creating nested structs automatically
cfg = struct();
cfg = setfield(cfg, "solver", "name", "cg");
cfg = setfield(cfg, "solver", "tolerance", 1e-6);
disp(cfg.solver.tolerance)Expected output:
1.0000e-06Updating an element of a struct array
people = struct("name", {"Ada", "Grace"}, "id", {101, 102});
people = setfield(people, {2}, "id", 999);
disp(people(2).id)Expected output:
999Assigning through a field that contains a cell array
data = struct("samples", {{struct("value", 1), struct("value", 2)}} );
data = setfield(data, "samples", {2}, "value", 10);
disp(data.samples{2}.value)Expected output:
10Setting an object property that honours access attributes
classdef Point
properties
x double = 0;
end
endExpected output:
3Using setfield with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how setfield changes the result.
Run a small setfield example, explain the result, then change one input and compare the output.
FAQ
Does setfield modify the input in-place?⌄
No. Like MATLAB, it returns a new struct (or object) with the requested update. In Rust this entails cloning the source value and mutating the clone.
Can I create nested structs in a single call?⌄
Yes. Missing intermediate structs are created automatically when you provide multiple field names, e.g. setfield(S,"outer","inner",value) builds outer when needed.
How do I update a specific element of a struct array?⌄
Supply an index cell before the first field name: setfield(S,{row,col},"field",value) is the same as S(row,col).field = value.
Does setfield work with handle objects?⌄
Yes. Valid handle objects forward the assignment to the underlying instance. Deleted or invalid handles raise the standard MATLAB-style error.
Can I index into field contents before continuing?⌄
Yes. Place a cell array of indices immediately after the field name. Each set of indices uses MATLAB's one-based semantics and supports the keyword end.
Why are GPU tensors gathered to the host?⌄
Assignments require host-side mutation. Providers can re-upload the updated tensor on subsequent GPU-aware operations; setfield itself never launches kernels.
Related Structs functions
fieldnames · getfield · isfield · orderfields · rmfield · struct
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how setfield is executed, line by line, in Rust.
- View the source for setfield 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.