function that returns the minimum elements of an array in matlab

In MATLAB, we can write a function that returns the minimum element(s) of an array. One straightforward algorithm to do this is to find the minimum element in the array, and then compare all elements to see if they're equal to the minimum. Here's an example implementation that takes an array as input and returns an array of the minimum element(s):

main.m
function minElements = findMinElements(arr)
% FINDMINELEMENTS Returns an array of the minimum element(s) in the input array.
%
% Inputs:
%    arr (Nx1 numeric array): The input array to find minimum element(s) in.
%
% Output:
%    minElements (Kx1 numeric array): The minimum element(s) in arr.

minValue = min(arr);
isMin = arr == minValue;
minElements = arr(isMin);
end
372 chars
14 lines

Let's go through this line-by-line to see what it does:

  1. function minElements = findMinElements(arr) - This is a function definition with two parts: the inputs (in this case, a single array arr) and the outputs (in this case, an array of the minimum elements, minElements).
  2. minValue = min(arr); - This finds the minimum value in the array using the built-in min function and assigns it to minValue.
  3. isMin = arr == minValue; - This creates a logical array isMin that is true wherever arr is equal to minValue.
  4. minElements = arr(isMin); - This selects only the elements of arr where isMin is true.

So if, for example, arr = [1 2 3 2 1], then this function would return [1 1], the two minimum values.

gistlibby LogSnag