Accessing multiple logical array indexing results at the same time
17 次查看(过去 30 天)
显示 更早的评论
For my application I'm working with a large array of signals stored inside of a cell array. I'm building a set of name-value pairs to pass to another function, so I'm using cells to store the signals that match certain names. I've used logical indexing successfully to grab one such signal, but I'd like to grab a full set of signals that all have different names. I've included a simplified example below illustrating what I'm trying to do and the error I get.
test = magic(4)
test =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
K>> equalToTwo = test == 2
equalToTwo =
4×4 logical array
0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 0
K>> equalToSixteen = test == 16
equalToSixteen =
4×4 logical array
1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
K>> tests = {equalToTwo,equalToSixteen}
tests =
1×2 cell array
[4×4 logical] [4×4 logical]
K>> test2 = test(tests{:})
Index exceeds matrix dimensions.
So from the example above, I have two logical arrays that should return one value each. I can use those arrays to index into the main array just fine with only one, but I'd like to be able to return n-number of values based on how many sets of logical arrays I have. This is a much simpler example, but I think it is easier to understand then trying to explain the larger set of code I'm working with and the problem presents in the same way.
0 个评论
采纳的回答
Paolo
2018-7-23
If I am understanding correctly the following code should solve your problem:
test = magic(4);
equalToTwo = find(test == 2);
equalToSixteen = find(test == 16);
tests = {equalToTwo,equalToSixteen};
test2 = test([tests{:}])
更多回答(1 个)
Walter Roberson
2018-7-23
If more than one logical value can be true, or if any of the entries might have no matches:
cellfun(@(mask) test(mask), tests, 'uniform', 0)
If each entry is certain to have exactly one match:
cellfun(@(mask) test(mask), tests)
2 个评论
Walter Roberson
2018-7-24
This is just applying each cell as logical indexing. Remember in MATLAB, indexing and function calls use the same syntax.
'uniform', 0 means that each output from the call should be placed into an individual cell entry. You need that unless the result of the expression is always guaranteed to be a scalar.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Testing Frameworks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!