# sub2ind - get all of 3rd dimension

5 views (last 30 days)
RuiQi on 16 May 2017
Edited: Guillaume on 17 May 2017
I have 2 matrices, one is a 2D matrix carrying an integer of labels and another a 3D matrix where each [row col] is a feature vector. I am trying to extract the feature vectors of a specific label. The result should be a matrix where either each row or column is the feature vector of a specific pixel. The sub2ind function does not allow me to easily extract it like below. I hope someone can assist me.
How else can I extract the vectors of every pixel given the row and column ?
[row, col] = find(label == 41);
% does not work
sub_feature_map = label(sub2ind(size(feature_map), row, col, :));

Andrei Bobrov on 16 May 2017
Edited: Andrei Bobrov on 16 May 2017
EDIT
without sub2und
l0 = label == 41;
k = size(feature_map,3);
sub_feature_map = reshape(feature_map(repmat(l0,1,1,k)),[],k);
[m,n,k] = size(feature_map);
[ii,jj] = find(repmat(label == 41,1,1,k));
sub_feature_map = reshape(feature_map(sub2ind([m,n,k],ii,rem(jj,n),ceil(jj/n))),[],k);

#### 1 Comment

RuiQi on 16 May 2017
I want to do this for example
A = B(1,2,:) % take the 3D content of B at [1,2] and pass it to A.
% Now A is a vector
How do I do it with sub2ind ?
A = B(sub2ind(size(B), 1, 2, :)); % colon does not work here
% A should have the contents [B(1,2,1), B(1,2,2), ... , B(1,2,end)];

Guillaume on 16 May 2017
Edited: Guillaume on 17 May 2017
You don't need sub2ind, simply use:
[rows, cols] = find(label == 41);
sub_feature_map = feature_map(rows, cols, :);
You can then reshape that into one column vector per pixel with:
sub_feature_map = reshape(permute(sub_feature_map, [3 2 1]), [], size(sub_feature_map, 3));

RuiQi on 16 May 2017
I initially tried that but I didn't get the right results. So my feature map is 321x481x144. My label map is 321x481. Below I have an image of the label map. If I use your suggestion: [rows, cols] = find(label == 41);
sub_feature_map = feature_map(rows, cols, :);
sub_feature_map becomes a matrix of 35x35x144. sub_feature_map should only be 35x144 since there are 35 pixels with label of 41 and there are 144 elements per pixel in feature_map. Gosh this is ridiculously hard.
Guillaume on 17 May 2017
How daft was I? Ignore my answer. Of course it doesn't work. You do need sub2ind. You just need to replicate the row and column vectors as many time as there are pages and replicate the page vectors accordingly:
[rows, cols] = find(label == 41);
npages = size(feature_map, 3);
sub_feature_map = feature_map(sub2ind(size(feature_map), ...
repmat(rows, npages, 1), ...
repmat(cols, npages, 1), ...
repelem((1:npages)', numel(rows))));
and then reshape.