Optimization Simple search
조회 수: 7 (최근 30일)
이전 댓글 표시
I got a quick question, lets say I have an array of numbers for example [ 9 3 2 7 1 8 ] and I want to find the minimum value ie: for this example it would be 1.
How could I implement an optimization search like this??
답변 (8개)
John
2011년 4월 20일
댓글 수: 12
Matt Fig
2011년 4월 22일
I just noticed that my function incorrectly handles NaN's if the input has only NaN and Inf - the index is always 1. This must be part of the reason why MIN is so much slower with two outputs... It is doing some gymnastics when NaN's are encountered.
Matt Tearle
2011년 4월 22일
Interesting! Thanks for the info. I did idly wonder if the number of outputs was making the difference, but couldn't see any reason why. Your explanation makes sense.
Paulo Silva
2011년 4월 20일
m=[9 3 2 7 1 8 ]
%another way to find minimum value, using unique
u=unique(m);
u(1)
%another way to find minimum value, using sort
s=sort(m);
s(1)
%another way to find minimum value, a loop this time
MinVal=m(1);
for lo=1:numel(m)
if m(lo)<MinVal
MinVal=m(lo);
end
end
MinVal
댓글 수: 1
Andrei Bobrov
2011년 4월 20일
or more loops for
k = sum(abs(m));
for jj = 1:numel(m)
k = min(k,m(jj));
end
Walter Roberson
2011년 4월 20일
If you use one of the optimizers that do not require continuous derivatives, then for any x value, take K = floor(x); if that is out of the range 1:length(m) return +infinity, and otherwise return m(K)
The optimization routine should then find the minimum value, and floor() of the x value it returns will be the index of that value.
댓글 수: 0
John
2011년 4월 21일
댓글 수: 6
Paulo Silva
2011년 4월 21일
m=randi([1 10],5,2) %x and y array
MinVal=m(1,2);
MinValRow=1;
for lo=1:size(m,1)
if m(lo,2)<MinVal
MinVal=m(lo,2);
MinValRow=lo;
end
end
MinValy=MinVal
MinValx=m(MinValRow,1)
MinValRow
John
2011년 4월 21일
댓글 수: 1
Paulo Silva
2011년 4월 21일
even after being warned about the inefficiency of that method you insist on using it!
Your function does work fine:
m=randi([1 10],10,2) %x and y array
y=bubble(m(:,1),m(:,2))
y(1) %min value
Paulo Silva
2011년 4월 21일
John code:
function y= bubble(x,y)
n = length(x);
for k = 1:n-1
for j = 1:n-k
if(x(j)> x(j+1))
temp = x(j);
x(j) = x(j+1);
x(j+1) = temp;
temp = y(j);
y(j) = y(j+1);
y(j+1) = temp;
end % if
end % for
end % for
y = x;
my code:
MinVal=m(1,2);
MinValRow=1;
for lo=1:size(m,1)
if m(lo,2)<MinVal
MinVal=m(lo,2);
MinValRow=lo;
end
end
Test with
n=1:2000
m=randi([1 10],n,2); %x and y array
![](https://www.mathworks.com/matlabcentral/images/broken_image.png)
You can see the time of code execution rising very fast with the bubble sort method, while with my code the time remains almost constant, better codes do exist and I bet that Matt Fig has better code :)
댓글 수: 0
John
2011년 4월 22일
댓글 수: 4
Walter Roberson
2011년 4월 22일
No, just a single pass through finding the minimum is *much* easier than sorting.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!