Find the minimum of 3 2d arrays at each position.
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Li zifan
il 24 Ago 2018
Commentato: Ji Hoon Jeong
il 28 Ago 2018
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
0 Commenti
Risposta accettata
Ji Hoon Jeong
il 24 Ago 2018
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
2 Commenti
Ji Hoon Jeong
il 28 Ago 2018
Thinking about "more than 2 minimum value" is a really smart move. In my example, function "min" is used to find the index of the minimum value. When there are more than 2 minimum values exist, the function returns the smallest index of the minimum value.
"If the minimum value occurs more than once, then min returns the index corresponding to the first occurrence."
-from matlab's min function document
values = [3,1,5,2,1,5];
[v,i] = min(values);
v = 1
i = 2 ( 2 and 5 has the same minimum value 1 )
Usually, this does not make any problem with your algorithm, but sometimes this can bias the output to the smaller index value. If this characteristic bothers you, then you should write custom min function.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!