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.m372 chars14 lines
Let's go through this line-by-line to see what it does:
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
).minValue = min(arr);
- This finds the minimum value in the array using the built-in min
function and assigns it to minValue
.isMin = arr == minValue;
- This creates a logical array isMin
that is true wherever arr
is equal to minValue
.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