# Extract specific data from 3D matrix

50 views (last 30 days)
Jan Kubicek on 30 Jan 2021
Commented: Jan Kubicek on 31 Jan 2021
I would like to kindly ask you for the help with the issue of extracting specific values from 3D matrix. I have the variable A(10,10,3) containing the elements 1, 2, 3, and the second variable B(10,10,3) containing pixel values. I need to extract and store the elements from each layer of B which are in the same position as elements 1 from A. Thus, these values should be stored in a cell array (it should contain 3 cells). I was able to perform this task for one 2D matrix, but in the case of 3D matrix I am not able to do that. I would like to kindly ask you for help.
Iuliu Ardelean on 30 Jan 2021
Could you give an example?

Iuliu Ardelean on 30 Jan 2021
size = 10;
A = randi(3, [size size 3]); % matrix containing elements 1, 2 and 3
B = randi(255, [size size 3]); % RGB matrix
[row, col] = find(A==1);
% I wasn't sure if you wanted to extract only one of R, G, or B,
% OR you wanted to extract all three R, G, and B at a same time...
% so option 1: if you want to extract only one of R, G, and B at a time:
pixel_values = zeros(size, size, 3);
pixel_values(A==1) = B(A==1)
% and option 2: if you want to extract all three R, G, and B at the same time:
pixel_values = zeros(size, size, 3);
col = mod(col,size); % this is because find returns linear indices if matrix is multidimensional
col(col == 0) = size;
pixel_values(row, col, :) = B(row, col, :)
Jan Kubicek on 30 Jan 2021
Thank you very much for the reaction. It is a nice approach. Nevertheless, I need to get only arrays of the pixels from each layer of B in the same positions as A==1 . I am using the first option, I tried to make a cell array, containg only these pixels, but it probably does not work well, please can you help me with that:
for i=1:3
pix{i}=pixel_values(pixel_values(:,:,i)>0);
end
My task is I need to compute histogram of the pixel values from each layer of the matrix B.
Thank you very much.

Walter Roberson on 31 Jan 2021
A = randi(4, 5,5,3)
A =
A(:,:,1) = 2 3 4 4 1 2 4 1 3 2 3 2 3 4 4 1 4 4 1 1 4 3 4 2 1 A(:,:,2) = 3 4 1 3 3 2 4 4 4 3 4 1 1 2 3 2 3 3 2 3 3 2 1 2 4 A(:,:,3) = 3 3 4 3 1 3 2 3 1 1 2 2 2 3 1 3 4 1 3 2 1 1 2 3 4
B = randi(9, 5,5,3)
B =
B(:,:,1) = 9 5 4 9 4 1 9 8 9 1 9 7 7 9 9 6 4 9 3 6 1 1 3 2 2 B(:,:,2) = 8 1 4 7 9 6 1 2 9 1 2 7 2 1 7 2 5 4 8 4 9 6 6 5 4 B(:,:,3) = 5 9 2 8 3 3 7 1 8 5 7 2 1 6 7 2 5 9 1 4 9 3 4 1 1
idx = find(A==1);
temp = B(idx);
[R,C,P] = ind2sub(size(A),idx);
pix = arrayfun(@(p) temp(P==p).', 1:max(P), 'uniform', 0);
celldisp(pix)
pix{1} = 6 8 3 4 6 2 pix{2} = 7 4 2 6 pix{3} = 9 3 9 8 3 5 7
##### 2 CommentsShowHide 1 older comment
Jan Kubicek on 31 Jan 2021
I would like to kindly thank you very much for your contributions, they work very well :-)