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

50 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 19 Apr 2018
Edited: Stephen23 on 19 Apr 2018
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:

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 19 Apr 2018
Edited: Stephen23 on 19 Apr 2018

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,:)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!