Accessing multiple logical array indexing results at the same time
16 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Paolo
on 23 Jul 2018
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{:}])
More Answers (1)
Walter Roberson
on 23 Jul 2018
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 Comments
Walter Roberson
on 24 Jul 2018
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.
See Also
Categories
Find more on Testing Frameworks 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!