MATLAB: Find the minimum of 3 2d arrays at each position.

minimum min 3d_array 2d_array

Hi, I have 3 2d arrays with same dimensions(or a 3d array with 3 layers), and I want to find the the minimum position of each point. e.g. function could tell which array (or layer has the minimum value of each point).
I know how to do that with for loop, but that cost a lot of time dealing with large scale arrays. So is there a more efficient way to do that?
D=rand(1000,1000,3);
[row,col,~]=size(D);
for i=1:row
for j=1:col
close=min(D(i,j,:)); %minimum value
if size(find(D(i,j,:)==close))==1 %if only one minimum
position(i,j)=(find(D(i,j,:)==close));
else
n=find(D(i,j,:)==close); %if 2 or more
position(i,j)=n(1);
end
end
end

Best Answer

Hi Li zifan
Your algorithm is fine, but several parts can be fixed to make it much faster.
1. Preallocation is critical In your code, the size of the variable "position" is not fixed. Please add this line before the for loops
position = zeros(1000,1000);
2. Less the number of functions, Faster the script if statement and 3 find function will slower your code
use
find(D(i,j,:)==close
code only once in your for loop
3. index of min value can be found by min function min function can spit out two output, one is min value itself, and the other one is location(=index) of the min value.
Altogether, faster version of your code
D=rand(1000,1000,3);
position = zeros(1000,1000);
[row,col,~]=size(D);
for i=1:row
for j=1:col
[~,index_of_min_value] = min(D(i,j,:));
position(i,j) = index_of_min_value;
end
end