フィルターのクリア

Look for minimum value in array

2 ビュー (過去 30 日間)
Mateusz Brzezinski
Mateusz Brzezinski 2020 年 9 月 2 日
Hello,
I have a function like this:
i=1;
Min=ones(1,200);
while i>=200
min_y = min(y(:,i));
pos_y = find(y(:,i)==min_y);
phi0s = x(pos_y ,i);
Min(1,i) = phi0s;
i=i+1;
end
Its job is to find a min value of y and as a results give a corresponding x value.
x and y are arrays with a dimension of n x 200 - let say that I stored results of 200 experiment in those two arrays and now I need to find smallest y value in each column and corresponding x.
Can I improve it somehow or even better run it without a loop? I will be grateful for any tips!

採用された回答

Rik
Rik 2020 年 9 月 2 日
Loops aren't slow. You generally only need to remove them if there are native functions that accept array inputs, which happens to be the case here:
%generate random data
n=4;
x=rand(n,200);
y=rand(n,200);
%your corrected code
i=1;
Min=ones(1,200);
while i<=200%why aren't you using a for-loop here?
min_y = min(y(:,i));
pos_y = find(y(:,i)==min_y);
phi0s = x(pos_y ,i);
Min(1,i) = phi0s;
i=i+1;
end
%vectorized
[~,idx]=min(y,[],1);
ind=sub2ind(size(x),idx,1:size(y,2));
Min2=x(ind);
isequal(Min2,Min)
  4 件のコメント
Image Analyst
Image Analyst 2020 年 9 月 2 日
And the 1 can be omitted
Min(i) = phi0s;
And you should probably use a for loop like he suggested, and use "col" or "column" for the column index rather than i which is the imaginary variable sqrt(-1). Or use the vectorized approach. It's more compact and cryptic than a for loop though. So use whatever you're comfortable with. For loops will be fast, particularly if there are only a microscopic 200 iterations.
Mateusz Brzezinski
Mateusz Brzezinski 2020 年 9 月 2 日
Ok, thanks I will do that

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2020 年 9 月 2 日
[Y,idx]=min(y);
X=x(length(y)*(0:length(idx)-1)+idx);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by