subsasgn

Assignment through an index structure, the function behind A(i) = v, A.f = v and A{i} = v.

Category: Programming > Classes

Syntax

B = subsasgn(A, S, V)

Returns a copy of A with the elements selected by S replaced by V.

Description

subsasgn is what the interpreter calls for an assignment with an index. Calling it directly is useful when the indexing is built at run time, for example when the field names or the number of levels are not known in advance.

Each element of S is one level: substruct('.', 'a', '()', {2}) stands for .a(2). A class can overload subsasgn to give its own meaning to assignment.

Input arguments

A
The array, struct, cell array or object to modify.
S
Structure array with fields type ('()', '{}' or '.') and subs, usually built with substruct. Several elements describe a chain.
V
The value to assign.

Output arguments

B
The modified copy. A itself is not changed.

Example

Changing an element and a nested cell

a = [10 20 30];
b = subsasgn(a, substruct('()', {2}), 99)
S.f = {1, 2};
T = subsasgn(S, substruct('.', 'f', '{}', {2}), 'new');
T.f
Output
b = 1×3

    10    99    30
ans = 1×2 cell

    {[1]}    {'new'}

Notes

MatLivre does not call a user-defined subsasgn for parenthesis assignment on objects, so a class overload does not take effect for obj(i) = v.

See also

subsref substruct numArgumentsFromSubscript setfield