remove rows in table based on different string across columns

1 view (last 30 days)
DavidL88
DavidL88 on 6 Nov 2021
Edited: DavidL88 on 7 Nov 2021
How do I remove any row in which one column contains either 11_right OR 21_right and the other column contains earlyP3? Drafted below code but doesn't work. I attach a sample table.
T(contains(string(T{:,2}),'11_right') & string(T{:,3}),'earlyP3') = [];
T(contains(string(T{:,2}),'21_right') & string(T{:,3}),'earlyP3') = [];

Accepted Answer

Dave B
Dave B on 7 Nov 2021
Edited: Dave B on 7 Nov 2021
You have a couple of bugs:
  • You need to write contains twice: it's not contains(thing,otherthing) & thing2,otherthing2 but instead contains(thing,otherthing) & contains(thing2,otherthing2)
  • You need a to tell MATLAB that you want the whole row, that means specifying a ,: when you provide the rows. That is T(rows,columns) and columns is all (even though you can't remove a partial row in a table).
A few tips:
  • contains is probably not exactly what you want here, but maybe suitable enough for your purposes. contains will match 11_right and also 311_right if you had that, because the latter 'contains' the former. Consider using strcmp or ismember for the more precise match. Even though it's maybe irrelevant for this dataset, one day you might copy this code and then you'll have potential for a scary hidden bug.
  • It's easier with this kind of logic to define some index variables, that can help you debug a little. Here I broke it into 2 variables, but you could even break it into 3 (making the earlyP3 one a variable too). I wasn't creative with the names!
  • You don't need to force your chars into strings as MATLAB will figure it out when you say contains, nothing wrong with this though!
load sampleT.mat
preheight=height(sampleT);
ind1 = contains(sampleT.Outcome, '11_right') & contains(sampleT.ROI, 'earlyP3');
ind2 = contains(sampleT.Outcome, '21_right') & contains(sampleT.ROI, 'earlyP3');
sampleT(ind1 | ind2,:) = [];
postheight = height(sampleT);
fprintf('%d rows removed\n', preheight - postheight)
5 rows removed

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!