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

조회 수: 4 (최근 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에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by