Clear Filters
Clear Filters

Finding index to minimum values in 3D array

4 views (last 30 days)
I have a 3D matrix, and I would like to find the index to the minimum value along the 3rd dimension. In other words, I would like to replace the following loop with a faster operation:
A = rand(10,8,3);
indexToMinIn3rdDim = NaN*ones(size(A,1), size(A,2));
for iRow = 1:size(A,1)
for iCol = 1:size(A,2)
indexToMinInVector = find((squeeze(A(iRow,iCol,:))) == min((squeeze(A(iRow,iCol,:)))));
indexToMinInVector = indexToMinInVector(1); % Only keep 1st index if the same min value occurs
indexToMinIn3rdDim(iRow,iCol) = indexToMinInVector;
end
end

Accepted Answer

Rik
Rik on 9 Mar 2018
The isequal function thinks the code below works.
A=rand(10,8,3);
[a,b]=min(A,[],3);
indexToMinIn3rdDim = NaN*ones(size(A,1), size(A,2));
for iRow = 1:size(A,1)
for iCol = 1:size(A,2)
indexToMinInVector = find((squeeze(A(iRow,iCol,:))) == min((squeeze(A(iRow,iCol,:)))));
indexToMinInVector = indexToMinInVector(1); % Only keep 1st index if the same min value occurs
indexToMinIn3rdDim(iRow,iCol) = indexToMinInVector;
end
end
isequal(indexToMinIn3rdDim,b)

More Answers (0)

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!