How to use setfield and getfield with colons or vector indices

1 回表示 (過去 30 日間)
SK
SK 2018 年 7 月 28 日
編集済み: SK 2018 年 7 月 28 日
There are times when getfield and set field are useful, but they are documented poorly. Suppose I have the following
>> s.a = 1;
>> s.b = 2;
>> s.c.d = 34;
>> sarray = [s,s,s,s,s];
>> getfield(sarray, {3}, 'a') % get s(3).a, fine
>> getfield(sarray, {3}, 'c', 'd') % get s(3).c.d, fine
however if I try to access or assign to multiple indices, getfield just gets the first of the indices and setfield generates an error. For example:
>> sarray = setfield(sarray, {3}, 'c', 'd', 50); % set s(3).c.d to 50, fine
>> x = getfield(sarray, {[3,4]}, 'c', 'd');
>> disp(x)
50
>> x = getfield(sarray, {':'}, 'c', 'd');
>> disp(x)
50
>> sarray = setfield(sarray, {[3,4]}, 'c', 'd', 50);
Error using setfield (line 56)
Expected one output from a curly brace or dot indexing expression, but
there were 2 results.
>> sarray = setfield(sarray, {':'}, 'c', 'd', 50);
Error using setfield (line 56)
Expected one output from a curly brace or dot indexing expression, but
there were 2 results.
The documentation does hint that array indices can be used:
"If you specify a single colon operator for an index input, enclose it in single quotation marks: ':'"
So I would expect that there is some way to get the fields from multiple structs. Does anyone know how?

回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by