MATLAB: Look for minimum value in array

findfunctionMATLABminwhile loop

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!

Best Answer

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)