通过函数输出对 MatLab 结构数组进行条件索引
Conditional indexing of MatLab structure array by function output
我目前正在 MatLab 的结构数组中组织异构数据,例如,
patient.name = 'John Doe';
patient.billing = 127;
patient.test = [79 75 73 180 178 177.5; 220 210 205 79 75 73; 180 178 177.5 20 210 205;];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68 70 68; 118 118 119; 172 170 169; 220 210 205];
假设我想做一些更高级的索引,我想看看每个病人的测试区域的大小。这些字段都有不同的大小,这就是为什么我想为每个患者使用不同的结构。
我想做一些类似的事情:
%This does not work
disp(patient([size(patient.test,1)]>3))
例如检查patient.test的数组是否超过3行,并使用得到的布尔数组索引整个结构体数组。我假设我的语法完全错误,但我还没有找到如何正确执行它的示例。帮助将不胜感激!
patient.test
将给出一个 comma-separated list of the field's contents. You can collect that list into a cell array and use cellfun
将 size
函数应用于每个单元格的内容:
>> sz = cellfun(@size, {patient.test}, 'UniformOutput', false);
>> celldisp(sz)
sz{1} =
3 6
sz{2} =
4 3
如果您只想显示尺寸,您可以使用 cellfun
应用一个 anonymous function 来实现:
>> cellfun(@(c) disp(size(c)), {patient.test})
3 6
4 3
根据字段大小获取索引:
>> ind = cellfun(@(c) size(c,1)>3, {patient.test})
ind =
1×2 logical array
0 1
然后
patient_selected = patient(ind);
或者,如果您更喜欢单行,
patient_selected = patient(cellfun(@(c) size(c,1)>3, {patient.test}));
我目前正在 MatLab 的结构数组中组织异构数据,例如,
patient.name = 'John Doe';
patient.billing = 127;
patient.test = [79 75 73 180 178 177.5; 220 210 205 79 75 73; 180 178 177.5 20 210 205;];
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68 70 68; 118 118 119; 172 170 169; 220 210 205];
假设我想做一些更高级的索引,我想看看每个病人的测试区域的大小。这些字段都有不同的大小,这就是为什么我想为每个患者使用不同的结构。
我想做一些类似的事情:
%This does not work
disp(patient([size(patient.test,1)]>3))
例如检查patient.test的数组是否超过3行,并使用得到的布尔数组索引整个结构体数组。我假设我的语法完全错误,但我还没有找到如何正确执行它的示例。帮助将不胜感激!
patient.test
将给出一个 comma-separated list of the field's contents. You can collect that list into a cell array and use cellfun
将 size
函数应用于每个单元格的内容:
>> sz = cellfun(@size, {patient.test}, 'UniformOutput', false);
>> celldisp(sz)
sz{1} =
3 6
sz{2} =
4 3
如果您只想显示尺寸,您可以使用 cellfun
应用一个 anonymous function 来实现:
>> cellfun(@(c) disp(size(c)), {patient.test})
3 6
4 3
根据字段大小获取索引:
>> ind = cellfun(@(c) size(c,1)>3, {patient.test})
ind =
1×2 logical array
0 1
然后
patient_selected = patient(ind);
或者,如果您更喜欢单行,
patient_selected = patient(cellfun(@(c) size(c,1)>3, {patient.test}));