Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setfield is not working

Tags:

struct

matlab

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.

like image 538
kenes Avatar asked Jun 19 '26 07:06

kenes


1 Answers

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);
like image 165
DVarga Avatar answered Jun 22 '26 01:06

DVarga