How to remove rows that do not contain or match a specific 'string'

43 次查看(过去 30 天)
What I am trying to do is remove rows in my cell array "Vars" that do not contain any of the values in the cell array "Names"
For example I have a an array of data ive created/imported
Vars=
'Subject' 'Mass' 'Height' 'Age'
'A' 90 170 20
'B' 100 182 20
'C' 85 180 21
'D' 80 185 21
'E' 79 175 20
But I only want a final array containing the values corresponding with the strings in the array "names"
Names=
'Subject'
'A'
'C'
'D'
So the final product should look like
FinalVars =
'Subject' 'Mass' 'Height' 'Age'
'A' 90 170 20
'C' 85 180 21
'D' 80 185 21
Thankyou in advance for your help,
Note** the string 'A', 'B' etc will most likely be a last name ie. 'smith' or 'john' etc.
  1 个评论
Stephen23
Stephen23 2018-4-19
编辑:Stephen23 2018-4-19
Storing numeric scalars in a cell array makes processing that data much more difficult. Some beginners like the idea of storing any headers and footers together with their data in a cell array, but it is really much simpler to keep numeric data stored in a numeric array, and the headers and footers in their own cell vectors.
Alternatively you could use a table, which is exactly designed for data arranged like yours:

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2018-4-19
编辑:Stephen23 2018-4-19

For a cell array you can use ismember:

Vars = {
'Subject' 'Mass' 'Height' 'Age'
'A' 90 170 20
'B' 100 182 20
'C' 85 180 21
'D' 80 185 21
'E' 79 175 20};
Names = {'Subject','A','C','D'};
idx = ismember(Vars(:,1),Names);
out = Vars(idx,:)

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by