RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

RunMat™ is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

LicensePrivacy
/
See all docs
Builtin Reference
    • fieldnames
    • getfield
    • isfield
    • orderfields
    • rmfield
    • setfield
    • struct
    • structfun

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

NameTypeRequiredDefaultDescription
SAnyYes—Input struct/object/struct-array target.
fieldPropertyNameYes—Field/property name to assign.
valueAnyYes—Assigned value.
pathAnyVariadic—Alternating field names and optional index-selector cells `{...}` for nested assignment.
SAnyYes—Input struct-array target.
index_selectorAnyYes—Leading index selector in a cell array, e.g. `{2}` or `{end}`.

Returns

NameTypeDescription
SAnyUpdated struct/object/array value.

Errors

IdentifierWhenMessage
RunMat:setfield:NotEnoughInputsInput does not provide at least one path component plus assigned value.setfield: expected at least one field name and a value
RunMat:setfield:FieldExpectedField/path arguments are missing after parsing selectors.setfield: expected field name arguments
RunMat:setfield:IndexSelectorTypeIndex selector is not provided as a cell array.setfield: indices must be provided in a cell array
RunMat:setfield:InvalidIndexIndex component is malformed, empty, unsupported, or not a positive integer.setfield: invalid index element
RunMat:setfield:FieldNameTypeField name is not a scalar string or 1-by-N char vector.setfield: expected field name
RunMat:setfield:IndexShapeIndexing rank/shape is unsupported for the targeted value.setfield: unsupported index shape for target value
RunMat:setfield:NonStructAssignmentAssignment target does not support struct-like field updates.Struct contents assignment to a non-struct object is not supported.
RunMat:setfield:IndexOutOfBoundsResolved index is outside bounds for target value.Index exceeds the number of array elements.
RunMat:setfield:MissingFieldIndexed assignment path references a missing field.Reference to non-existent field
RunMat:PropertyPrivateAccessProperty exists but get/set access is private.setfield: private property access denied
RunMat:PropertyStaticAccessProperty exists but is static and cannot be assigned through an instance.setfield: static property access denied
RunMat:setfield:ObjectPropertyObject property operation is invalid (static, non-public, or malformed setter result).setfield: invalid object property operation
RunMat:setfield:InvalidHandleHandle target is invalid/deleted/null.setfield: invalid or deleted handle object
RunMat:setfield:InternalErrorInternal 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) mirrors S.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) or setfield(S,{1,3},"field",value), and accept the keyword end.
  • 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) matches S.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.
  • Assigned values retain their complete class and payload, including all eight integer classes. Numeric selectors inside index cells accept integer classes and are validated as exact one-based structural indices before host indexing.

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:

42

Creating 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-06

Updating 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:

999

Assigning 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:

10

Setting an object property that honours access attributes

classdef Point
    properties
        x double = 0;
    end
end

Expected output:

3

Using 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 · structfun

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.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • How setfield works
  • Does RunMat run setfield on the GPU?
  • GPU memory and residency
  • Examples
  • Assigning a new field in a scalar struct
  • Creating nested structs automatically
  • Updating an element of a struct array
  • Assigning through a field that contains a cell array
  • Setting an object property that honours access attributes
  • Using setfield with coding agents
  • FAQ
  • Related Structs functions
  • Open-source implementation
  • About RunMat