1. Structure declaration:
s = struct('field1', value1, 'field2', value2, ....) // create structure with fields and appropriate values
s = struct('field1', {}, 'field2', {},...) //create structure with empty values for each field
s = struct // create structure with empty field
s = struct([]) //create empty structure
s = struct
Example 1:
stuMyStruct = struct('color', {'red', 'green', 'yellow'}, 'type', 1)
Results:
stuMyStruct is structure array with:
stuMyStruct(1):
color: 'red'
type: 1
stuMyStruc(2):
color: 'green'
type: 1
stuMyStruct(3):
color: 'yellow'
type: 1
Example 2:
stuMyStruct = struct('color', {'red', 'green', 'yellow'}, 'type', {1, 2, 3})
Results:
stuMyStruct is structure array with:
stuMyStruct(1):
color: 'red'
type: 1
stuMyStruc(2):
color: 'green'
type:2
stuMyStruct(3):
color: 'yellow'
type: 3
Example 3:
stuMyStruct.color
Results:
ans = red
ans = green
ans = yellow
2. Access structure
There are two ways to access structure fields: by specifying field name or by dynamic field name. Here, we mention the dynamic field name because of the easy of the first way.
Example 4:
stuMyStruct = struct('color', 'red', 'type', 1)
strNewField = 'weight';
stuMyStruct.(strNewField) = 100;
Results:
stuMyStruct =
color: 'red'
type: 1
weight: 100
Note: distinguish from this case
stuMyStruct = struct('color', 'red', 'type', 1)
strNewField = 'weight';
stuMyStruct.strNewField = 100;
leads to this result
stuMyStruct =
color: 'red'
type: 1
strNewField : 100
3. Some other functions for field process
fieldnames: list all field name, type and attributes of structure or structure array
setfield: set value to field (very strong)
getfield: get value of specified field (very strong)
isfield: check the existence of a fieldname
orderfields: reorder the fieldnames
rmfield: remove specified fieldname
isstruct: determine whether input is a structure array
Refercences:

Không có nhận xét nào:
Đăng nhận xét