How to slice an array across multiple dimensions with two limit arrays?
3 views (last 30 days)
Show older comments
I'm interested in taking an arbitrary N-dimensional array, and two 1xN vectors, and using the two vectors as start/stop indices to slice the array, but I'm not sure how. Here's what I mean:
Let X be an N-dimensional array.
Let A and B be 1xN vectors like so:
A=[a1, a2, ..., aN]
B=[b1, b2, ..., bN]
How do I slice X such that I get this:
Y = X(a1:b1, a2:b2, ..., aN:bN)
I tried X(A:B), but that doesn't work - not even sure what that operation is doing, but it isn't doing what I want. I tried to think of some way to do it with logical indexing, but nothing simple came to mind. I could slice the array one dimension at a time in a loop, but it seems like there must be a one-liner. Thanks!
0 Comments
Accepted Answer
Bruno Luong
on 22 Apr 2022
Edited: Bruno Luong
on 22 Apr 2022
This should work
X=rand(6,6,6);
A=[1 2 3]; B=[6 5 4];
cidx = arrayfun(@(i1,i2) i1:i2, A, B, 'unif', 0);
Y = X(cidx{:})
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!