Why is there no need to define fields of structures before assigning them?

前端 未结 2 1362
后悔当初
后悔当初 2021-01-23 03:24

I am working with somebody else\'s code in MATLAB and it looks like he is creating structures, just by using field names without declaring them at all. Is that how it works in M

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 04:04

    Yes, field names are dynamic in MATLAB and can be added or removed at any time.

    %// Construct struct with two fields
    S = struct('one', {1}, 'two', {2});
    
    %// Dynamically add field
    S.three = 3;
    
    %// Remove a field
    S = rmfield(S, 'two')
    

    The only constraint is that if you have an array of structs, they all have to have the same field names.

    %// Create an array of structures
    S(1).one = '1.1';
    s(2).one = '1.2';
    
    %// Dynamically add a new field to only one of the structs in the array
    s(1).two = '2.1';
    
    %// s(2) automatically gets a "two" field initialized to an empty value
    disp(s(2))
    
    %//     one: '1.2'
    %//     two: []
    

    Also, MATLAB uses dynamic typing so there is no need to define the type of any variable or the fields of a struct ahead of time.

提交回复
热议问题