Home > database >  Conditional indexing of MatLab structure array by function output
Conditional indexing of MatLab structure array by function output

Time:10-14

I am currently organizing heterogeneous data in structure arrays in MatLab, e.g.,

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];

Let's assume I want to do some more advanced indexing, I want to look at the size of the test field of each patient. These fields all have heterogeneous sizes, which is why I want to use a different struct for each patient.

I want to do something along the lines of this:

%This does not work
disp(patient([size(patient.test,1)]>3))

For example, check whether the array of patient.test has more than 3 rows and use the resulting boolean array to index the entire structure array. I assume my syntax is simply wrong, but I have not found examples on how to do it properly. Help would be appreciated!

CodePudding user response:

patient.test will give a comma-separated list of the field's contents. You can collect that list into a cell array and use cellfun to apply the size function to the contents of each cell:

>> sz = cellfun(@size, {patient.test}, 'UniformOutput', false);
>> celldisp(sz)
sz{1} =
     3     6
sz{2} =
     4     3

If you only want to display the sizes, you can use cellfun to apply an anonymous function that does that:

>> cellfun(@(c) disp(size(c)), {patient.test})
     3     6
     4     3

To obtain an index based on the size of the field:

>> ind = cellfun(@(c) size(c,1)>3, {patient.test})
ind =
  1×2 logical array
   0   1

and then

patient_selected = patient(ind);

or, if you prefer it in a single line,

patient_selected = patient(cellfun(@(c) size(c,1)>3, {patient.test}));
  • Related