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

假如想象 提交于 2019-12-20 03:16:47

问题


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 MATLAB, you just start using case-insensitive field names of your choice?

So, for example, he has something like this:

classdef Emitter
   properties
      transients=[];
   end
end

... some other class
   methods
      function sound=makeSound()
         emitterthing.transients.receivedIntensity = 100
         emitterthing.transients.frequency = 500
      end
   end 

In other words, he just starts making up field names and assigning values to them without declaring the field names or their type.

Is that how it works in MATLAB?


回答1:


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.




回答2:


You need to distinguish between structs which are just a convenient way of storing data (functionality covered by suever's answer) and instances of classes. A struct is also an instance of a class, but all properties are dynamic properties by design and you don't need to worry about it. That is not always the case.

For example, if you'd create a gui from scratch with a lot a gui elements within a figure, you need to pass around a lot of properties and values in-between the gui elements. On thing all elements have in common is the figure they are placed in. It's handle, the handle of the current figure, an instance of the figure class, can be easily obtained by gcf in every callback function of the gui. So it would be convenient to use this handle to pass all information around within the gui.

But you can't just do:

h = figure(1);
h.myData = 42;

because the figure class does not provide the dynamic property myData - you need to define it:

h = figure(1);
addprop(h,'myData');
h.myData = 42;

I hope the difference is clear now.



来源:https://stackoverflow.com/questions/37312763/why-is-there-no-need-to-define-fields-of-structures-before-assigning-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!