这些“新名称”和“[]”来自哪里?
Where are these `New Name` and `[]` coming from?
我正在学习结构迭代,并尝试在循环中输出东西
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
fields = fieldnames(patient)
%numel is number of elements
for i=1:numel(fields)
fields(i)
patient.(fields{i})
end
在此 patient.(fields{i})
期间,它给出了 'New Name'
和 []
,它们不属于我的 struct
。这些值从何而来?
输出为:
ans = 'name'
ans = John Doe
ans = Ann Lane
ans = New Name
ans = 'billing'
ans = 127
ans = 28.5000
ans = []
ans = 'test'
ans = 79.0000 75.0000 73.0000
180.0000 178.0000 177.5000
220.0000 210.0000 205.0000
ans = 68 70 68
118 118 119
172 170 169
ans = []
您之前必须分配 patient(3).name = 'New Name'
,并且由于您的代码仅 over-writes patient
的第一个和第二个元素,第三个元素保持不变,因此会出现在您的循环中。
您可以使用 size
或 numel
进行检查
numel(patient)
% 3
为防止这种情况,您可以在赋值
之前将 struct
初始化为空 struct
% Initialize it
patient = struct()
% Now populate
patient(1).name = 'whatever';
或者显式清除变量 clear patient
以确保不会发生这种情况。
clear patient
% Now populate it
patient(1).name = 'whatever';
另外,作为一个side-note,其他字段是[]
的原因是,如果你在现有的struct
数组中添加一个新字段,那么所有struct
数组中的条目将收到 []
作为新字段的值
clear patient
patient(2).name = 'New Name';
patient(1).name = 'Test';
% Add a new field only to patient(2)
patient(2).date = 'today';
% patient(1).date becomes []
patient(1).date
% []
我正在学习结构迭代,并尝试在循环中输出东西
patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169];
fields = fieldnames(patient)
%numel is number of elements
for i=1:numel(fields)
fields(i)
patient.(fields{i})
end
在此 patient.(fields{i})
期间,它给出了 'New Name'
和 []
,它们不属于我的 struct
。这些值从何而来?
输出为:
ans = 'name'
ans = John Doe
ans = Ann Lane
ans = New Name
ans = 'billing'
ans = 127
ans = 28.5000
ans = []
ans = 'test'
ans = 79.0000 75.0000 73.0000
180.0000 178.0000 177.5000
220.0000 210.0000 205.0000
ans = 68 70 68
118 118 119
172 170 169
ans = []
您之前必须分配 patient(3).name = 'New Name'
,并且由于您的代码仅 over-writes patient
的第一个和第二个元素,第三个元素保持不变,因此会出现在您的循环中。
您可以使用 size
或 numel
numel(patient)
% 3
为防止这种情况,您可以在赋值
之前将struct
初始化为空 struct
% Initialize it
patient = struct()
% Now populate
patient(1).name = 'whatever';
或者显式清除变量 clear patient
以确保不会发生这种情况。
clear patient
% Now populate it
patient(1).name = 'whatever';
另外,作为一个side-note,其他字段是[]
的原因是,如果你在现有的struct
数组中添加一个新字段,那么所有struct
数组中的条目将收到 []
作为新字段的值
clear patient
patient(2).name = 'New Name';
patient(1).name = 'Test';
% Add a new field only to patient(2)
patient(2).date = 'today';
% patient(1).date becomes []
patient(1).date
% []