How to use a 2D index to create a 3D array from a 4D array?

Hello,
I have a main 4D array A with size
200x300x3x5
and I want to create a 3D array C of size
200x300x3
using a 2D array index that picks one specific set of the 4D array A to keep to make C.
I have a 2D index array B with size
200x300
, and all elements of B range from 1 to 5 (i.e. size of the 4th dimension of A). Each element in B indicates to which set of the 4th dimension element I want to access from A to use to create C.
I want to avoid using loops to reduce run time but at the same time I'm also lost as to how to do this.
I tried
C(:,:,:) = (A(B))
and
C(:,:,:) = (A(:,:,:,B))
but neither seem to do what I want it to do.

2 件のコメント

Guillaume
Guillaume 2019 年 9 月 12 日
Why is the index 2d and not 3d? Is it the same 4th dim index you want to pick for all 3 pages? I.e. should the index be repmat'ed across the 3rd dimension?
Janette Lin
Janette Lin 2019 年 9 月 12 日
The each of the 4th dimension is the same for all 3 pages

サインインしてコメントする。

回答 (1 件)

Bruno Luong
Bruno Luong 2019 年 9 月 12 日
編集済み: Bruno Luong 2019 年 9 月 12 日

1 投票

It's amazing you all ask the same question, it must have some competition somewhere in the world (china?) about the topic of processing a stack of RGB images.
[m,n,p,~] = size(A);
x = m*n*p;
C = reshape(A((1:x)'+x*(repmat(B(:)-1,p,1))),[m,n,p]);

5 件のコメント

Bob Thompson
Bob Thompson 2019 年 9 月 12 日
Ha, I totally recognized the question too while I was reading it.
Bruno Luong
Bruno Luong 2019 年 9 月 12 日
I detect at least three guys around the table. ;-)
Janette Lin
Janette Lin 2019 年 9 月 13 日
What does this bit in your third line of your code do?
(1:x)'+x*(repmat(B(:)-1,p,1))
Bruno Luong
Bruno Luong 2019 年 9 月 13 日
編集済み: Bruno Luong 2019 年 9 月 13 日
it computes the linear-index of each voxel on the "page" B.
You might interest in Andrei's use of NDGRID and SUB2IND. This is clearer coding though it requires 4/5 big temporary arrays.
My code is then more obscure but faster.
Andrei Bobrov
Andrei Bobrov 2019 年 9 月 13 日
+1

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeMatrices and Arrays についてさらに検索

製品

リリース

R2019a

質問済み:

2019 年 9 月 12 日

コメント済み:

2019 年 9 月 13 日

Community Treasure Hunt

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

Start Hunting!

Translated by