setfield is not working

时间:2016-08-31 12:07:25

标签: matlab struct

I have a.b, a three element vector. I want to change first 2 elements. Code in the third line does not include the change in second line. For instance, second line responds as:

[2 0 0]

Third line responds as:

[0 3 0]

My code is as follows.

a.b = [0 0 0]
setfield(a,'b',{1},2)
setfield(a,'b',{2},3)

This code is an example. It is to illustrate the problem.

2 个答案:

答案 0 :(得分:5)

You can correct it as

a.b = [0 0 0];
a = setfield(a, 'b', {1}, 2);
a = setfield(a, 'b', {2}, 3);

From the help of setfield:

S = setfield(S,'field',V) sets the contents of the specified field to the value V. This is equivalent to the syntax S.field = V. S must be a 1-by-1 structure. The changed structure is returned.

Without capturing the return value, the first setfield call will assign the modified struct to the ans variable.

Therefore the following code also works, but should be avoided:

a.b = [0 0 0];
setfield(a, 'b', {1}, 2);
a = setfield(ans, 'b', {2}, 3);

答案 1 :(得分:0)

An bit faster alternativ to setfield() would be

a.b(1:2) = [2 3]

or if the index isn't in a sequence

a.b([1 3]) = [2 5]

相关问题