Monday, March 28, 2011

Subscripted assignment between dissimilar structures

Look at the following two MATLAB examples.
clear a g
a.b =[1 2 3];
a.c ='example';

g =struct('c', '', 'b', zeros(1, 3));
g(1) =a
***************************
clear a g
a.b =[1 2 3];
a.c ='example';

g =struct('b', zeros(1, 3), 'c', '');
g(1) =a
 
These two scripts are the same except slight difference that the order of the structure of g is defined.

When the first one is called, MATLAB will throw an error:
??? Subscripted assignment between dissimilar structures.
 
However, the second one can run without any error. That is, this error can be solved by changing the order of the structure definition.

The other way to solve this problem is calling the function s = orderfields(s1) when defining the struct.

No comments:

Post a Comment