Find the minimum of 3 2d arrays at each position.
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Ji Hoon Jeong
2018-8-24
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 个评论
Ji Hoon Jeong
2018-8-28
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!