Gregor Isack
Gregor Isack

Reputation: 1131

Extract column of matrices from a 3D indexes

I try to extract columns of matrices(in 2D) from a set of given indices(in 3D), without converting the 2D matrix into 3D so as to efficiently use memory (I'm dealing with very huge data), can I achieve this? I'll reuse the 2D matrix for each slice of the 3D matrix, but I just don't know how to do it. Example code:

A=rand(9,100); %The matrix that will be reused
B=randi([1 100],[1 100 30]); %the indices
Extracted=A(:,B); %this part I can't seem to solve it yet

Expected output of Extracted would be 9x100x30. Any idea guys? Thanks in advance!

Upvotes: 1

Views: 27

Answers (1)

OmG
OmG

Reputation: 18838

A solution can be using inline function and arrayfun:

A=rand(9,100); %The matrix that will be reused
B=randi([1 100],[1 100 30]); %the indices
func = @(x) A(x);
Extracted = arrayfun(func, B);

Another solution is convert 3D matrix B to a vector. Then using your method to retrieve Extracted:

A=rand(9,100); %The matrix that will be reused
B=randi([1 100],[1 100 30]); %the indices
idx = reshape(B,1,numel(B));
Extracted = A(idx);

Upvotes: 2

Related Questions