Logical indexing in tables with multiple targets
24 views (last 30 days)
Show older comments
Suppose you have a table such as the one below:
Sample = [0;1;1;2;2;2];
Data = [rand(1,5);rand(1,5);rand(1,5);rand(1,5);rand(1,5);rand(1,5)];
A = table(Sample,Data)
Now say you want to extract only a subset a data that corresponds to certain Sample numbers. I know of a coup[le ways to do this.
You can do row-wise deletion if your table isn't too large and you know the row numbers of what you want to delete. Or you can just call the rows that you care about and assign it to a new table.
B = A;
B(1:3,:) =[]; %This deletes the Samples 0 and 1, but leaves 2.
B
B = A;
B = B(4:6,:)
But if your table is large, I prefer to use some logical indexing:
B = A;
B = A(A.Sample == 2,:)
Now what if I want to have multiple targets in the mask of my logical lindex. I know I can combine multiple logical indicies (indexes?) as below, but then how do I pass that along to the table?
B = A;
C = A.Sample == 0;
D = A.Sample == 2;
E = C|D
B = B(B.Sample(E),:)
Really, I am hoping there is a way to make the following workflow happen without going through for loops for each target of my logical index, but I might have to homebrew my own function to accomplish this.
C = [1,5,23]; % An array of the Sample numbers I'd like to keep in my new table
B = A(A.Sample == C,:);
If anyone knows a better way to do this so I can avoind clunky blocks in my script that will piecewise pull out the bits that I need, I would really appreciate it. Thanks in advance!
0 Comments
Accepted Answer
Bruno Luong
on 1 Sep 2023
Edited: Bruno Luong
on 1 Sep 2023
Note that what I wrote here is very similar to standard array.
Sample = [0;1;1;2;2;2];
Data = [rand(1,5);rand(1,5);rand(1,5);rand(1,5);rand(1,5);rand(1,5)];
A = table(Sample,Data)
B = A;
C = A.Sample == 0;
D = A.Sample == 2;
E = C|D
B = B(E,:) % Fix your error
C = [1,5,23]; % An array of the Sample numbers I'd like to keep in my new table
B = A(ismember(A.Sample,C),:) % This will meet your last wish
More Answers (0)
See Also
Categories
Find more on Logical 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!