How to use setfield and getfield with colons or vector indices

3 visualizaciones (últimos 30 días)
SK
SK el 28 de Jul. de 2018
Editada: SK el 28 de Jul. de 2018
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?

Respuestas (0)

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by