How to populate 2d-array from 3d array with page indices

1 view (last 30 days)
Hi!
Please see my example below. I start with a non-scalar structure, which I concatenate into a 3d-array. I then find the minimum values and their indices in the 3rd dimension using 'min'. Then, from a second array of exactly the same size, I want to extract a new array with entries corresponding to indices in the min value indices from the other array. I can do this perfectly well with the loop below, but doing it by vectorization would be twice as fun :)
The values in 'b' array is chosen to better illustrate the problem, as it is directly related to the 'pageIdx' array.
BR Andreas.
s(1).f=rand(2);
s(2).f=rand(2);
s(3).f=rand(2);
a=cat(3,s.f);
b=ones(2,2,3);
b(:,:,2)=2;
b(:,:,3)=3;
[minVals,pageIdx]= min(a,[],3)
bSize = size(b); nRows = bSize(1); nCols = bSize(2);
bMinVals = zeros(nRows,nCols);
for iRow = 1:nRows
for jCol = 1:nCols
bMinVals(iRow,jCol)=b(iRow,jCol,pageIdx(iRow,jCol));
end
end
bMinVals == pageIdx

Accepted Answer

Guillaume
Guillaume on 23 Feb 2015
a = rand(2, 2, 3);
b = ones(2, 2, 3); b(:, :, 2) = 2; b(:, :, 3) = 3;
b= -b; %to differentiate from PageIdx
[minVals, PageIdx] = min(a, [], 3);
[r, c] = ndgrid(1:size(b, 1), 1:size(b, 2));
bMinVals = reshape(b(sub2ind(size(b), r(:), c(:), PageIdx(:))), size(b, 1), [])
isequal(bMinVals, -PageIdx)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!