Logical indexing in tables with multiple targets
25 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Bruno Luong
2023-9-1
编辑:Bruno Luong
2023-9-1
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!