Filter on words in Matlab tables (as in Excel)

2019-07-24 19:38发布

In Excel you can use the "filter" function to find certain words in your columns. I want to do this in Matlab over the entire table.

Using the Matlab example-table "patients.dat" as example; my first idea was to use:

patients.Gender=={'Female'}

which does not work.

strcmp(patients.Gender,{'Female'})

workd only in one column ("Gender").

My problem: I have a table with different words say 'A','B','bananas','apples',.... spread out in an arbitrary manner in the columns of the table. I only want the rows that contain, say, 'A' and 'B'.

It is strange I did not find this in matlab "help" because it seems basic. I looked in stackedO but did not find an answer there either.

2条回答
女痞
2楼-- · 2019-07-24 20:17

Here is a simpler, more elegant syntax for you:

matches = ((patients.Gender =='Female') & (patients.Age > 26));
subtable_of_matches = patients(matches,:);

% alternatively, you can select only the columns you want to appear,
% and their order, in the new subtable.
subtable_of_matches = patients(matches,{'Name','Age','Special_Data'});

Please note that in this example, you need to make sure that patients.Gender is a categorical type. You can use categorical(variable) to convert the variable to a categorical, and reassign it to the table variable like so:

patients.Gender = categorical(patiens.Gender);

Here is a reference for you: https://www.mathworks.com/matlabcentral/answers/339274-how-to-filter-data-from-table-using-multiple-strings

查看更多
Root(大扎)
3楼-- · 2019-07-24 20:22

A table in Matlab can be seen as an extended cell array. For example it additionally allows to name columns.

However in your case you want to search in the whole cell array and do not care for any extra functionality of a table. Therefore convert it with table2cell.

Then you want to search for certain words. You could use a regexp but in the examples you mention strcmp also is sufficient. Both work right away on cell arrays.

Finally you only need to find the rows of the logical search matrix.

Here the example that gets you the rows of all patients that are 'Male' and in 'Excellent' conditions from the Matlab example data set:

patients = readtable('patients.dat');
patients_as_cellarray = table2cell(patients);
rows_male = any(strcmp(patients_as_cellarray, 'Male'), 2); % is 'Male' on any column for a specific row
rows_excellent = any(strcmp(patients_as_cellarray, 'Excellent'), 2); % is 'Excellent' on any column for a specific row
rows = rows_male & rows_excellent; % logical combination
patients(rows, :)

which indeed prints out only male patients in excellent condition.

查看更多
登录 后发表回答