MATLAB Answers

How to use setfield and getfield with colons or vector indices

조회 수: 3(최근 30일)
SK
SK 28 Jul 2018
편집: SK 28 Jul 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?

  댓글 수: 0

로그인 to comment.

답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by