Filter on words in Matlab tables (as in Excel)

僤鯓⒐⒋嵵緔 提交于 2020-01-04 15:49:12

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28463921/filter-on-words-in-matlab-tables-as-in-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!