为什么在分配结构之前不需要定义结构的字段?

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

我正在 MATLAB 中使用其他人的代码,看起来他正在创建结构,只是使用字段名称而根本没有声明它们。这就是它在 MATLAB 中的工作方式,您只是开始使用您选择的不区分大小写的字段名称吗?

所以,例如,他有这样的东西:

classdef Emitter
   properties
      transients=[];
   end
end

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

换句话说,他只是开始编写字段名称并为其赋值,而没有声明字段名称或它们的类型。

它在 MATLAB 中是这样工作的吗?

是的,字段名称 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')

唯一的限制是,如果您有一个 array 结构,它们都必须具有相同的字段名称。

%// 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: []

此外,MATLAB 使用动态类型,因此无需提前定义任何变量的类型或 struct 的字段。

你需要区分structs which are just a convenient way of storing data (functionality covered by ) and instances of classes。结构也是 class 的实例,但所有属性都是 动态属性 设计的,您无需担心关于它。情况并非总是如此。

例如,如果您要从头开始创建一个图形用户界面,其中包含很多图形用户界面元素,则需要在图形用户界面元素之间传递大量属性和值。所有元素的共同点是它们所在的图形。它的句柄,当前图形的句柄,图形的实例class,可以通过每个回调函数中的gcf轻松获得的图形用户界面。所以使用这个句柄在 gui 中传递所有信息会很方便。

但你不能只做:

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

因为图class没有提供 dynamic property myData - you need to define it:

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

我希望现在区别很明显。