By Carey Smith
MATLAB has a built-in minimum function, of course. This example shows how you could write your own minimum function. This kind of logic might be applied to other kinds of searches of a data vector. This algorithm works on a vector input only. It returns both the minimum value and its index.
A key idea is to use the first element of the vector as a candidate for the minimum value, then search for values less that the candidate value. If such a value is found, then the new, smaller value replaces the candidate value .
function [x_min, k_min] = my_min(x)
% x = data vector (1xn or nx1)
% x_min = the minimum value of x
% i_min = the index of the minimum value of x
x_min = -inf;
k_min = -1;
% Is x 1-Dimensional?
[m_rows, n_cols] = size(x);
% If both the number of row and
% number of columns are > 1,
% then the vector is 2D
if( (m_rows > 1) & (n_cols > 1) )
disp('Error: input is not 1-Dimensional');
% If it get this far, then the vector is 1-Dimensional
k = 1; % 1st index into the input vector
x_min = x(k); % Initialize the min value to the first value
k_min = k;
n = length(x);
% This loop compares each value to the current min.
for k= 2:n % Start with k=2, because we initialed to k=1
if(x(k) < x_min) % Is this value bigger than min so far?
x_min = x(k); % Reset the min so far to this value
k_min = k;
end % end of function
Try testing it with this input vector:
x = [3,2,3,5,6,4,1,4]
[x_min, idx_min] = my_min(x)
Modify the my_min example function to create a function m-file that finds the maximum of a vector input.
Add texts here. Do not delete this text first.