defining a stuct variable

4 views (last 30 days)
Bashir Mohammad Sabquat Bahar Talukder
Answered: Steven Lord on 13 Nov 2019
Consider the following definition of a stucture variable-
>> spcase = struct('enable',true, 'vendors',{'IDT'},'trainOp',{'RTNV', 'RTLV', 'RTHV'}, 'testOp',{'RTNV', 'RTLV', 'RTHV'},'fnum', 1:8);
>> spcase
spcase =
1×3 struct array with fields:
enable
vendors
trainOp
testOp
fnum
Now, I am defining the same sturcture variable as folows-
>> spcase = struct('enable',true,'fnum', 1:8);
spcase.vendors = {'IDT'};
spcase.trainOp = {'RTNV', 'RTLV', 'RTHV'};
spcase.testOp = {'RTNV', 'RTLV', 'RTHV'};
>> spcase
spcase =
struct with fields:
enable: 1
fnum: [1 2 3 4 5 6 7 8]
vendors: {'IDT'}
trainOp: {'RTNV' 'RTLV' 'RTHV'}
testOp: {'RTNV' 'RTLV' 'RTHV'}
Could anyone clarify me, why I am observing this mismatch?

Answers (1)

Steven Lord
Steven Lord on 13 Nov 2019
From the documentation for the struct function, when you have multiple fields being created in the same struct call:
"If any of the value inputs is a nonscalar cell array, then s has the same dimensions as that cell array. Also, if two or more value inputs are nonscalar cell arrays, then they all must have the same dimensions.
For any value that is a scalar cell array or an array of any other data type, struct inserts the contents of value in the relevant field for all elements of s. For example, s = struct('x',{'a','b'},'y','c') returns s(1).x = 'a', s(2).x = 'b', s(1).y = 'c', and s(2).y = 'c'."
In your first example,
>> spcase = struct('enable',true, ... % array of any other data type
'vendors',{'IDT'},... % scalar cell array
'trainOp',{'RTNV', 'RTLV', 'RTHV'}, ... % nonscalar cell array
'testOp',{'RTNV', 'RTLV', 'RTHV'},... % nonscalar cell array
'fnum', 1:8); % array of any other data type
both the nonscalar cell arrays have the same dimensions, so the struct that is created has that same dimension and each of the other fields have the same value in each element of the struct array.
In your second example,
you create a scalar struct array then assign values to its fields. That post-creation assignment does not behave the same way (turning it into a nonscalar struct array) as creating it as a nonscalar struct in the first place.
If you want your first example to behave like your second, wrap the nonscalar cell arrays inside a scalar cell array.
>> spcase = struct('enable',true, ... % array of any other data type
'vendors',{'IDT'},... % scalar cell array
'trainOp',{{'RTNV', 'RTLV', 'RTHV'}}, ... % scalar cell array
'testOp',{{'RTNV', 'RTLV', 'RTHV'}},... % scalar cell array
'fnum', 1:8); % array of any other data type

Categories

Find more on Structures in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!