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
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.
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.