How to slice an array across multiple dimensions with two limit arrays?

19 次查看(过去 30 天)
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!

采纳的回答

Bruno Luong
Bruno Luong 2022-4-22
编辑:Bruno Luong 2022-4-22
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{:})
Y =
Y(:,:,1) = 0.7739 0.3475 0.5936 0.5165 0.5514 0.0120 0.8295 0.7020 0.7219 0.0188 0.0139 0.2095 0.6081 0.2888 0.2122 0.9462 0.7840 0.4617 0.7677 0.1717 0.3399 0.1233 0.8264 0.1021 Y(:,:,2) = 0.8648 0.4441 0.7968 0.1729 0.2677 0.8310 0.6914 0.3000 0.7044 0.0935 0.5411 0.2597 0.1844 0.8915 0.9166 0.0287 0.8937 0.8579 0.5319 0.6198 0.1937 0.8000 0.0968 0.2708

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by