To find the two biggest numbers in an array in Matlab, we can use the max
function to retrieve the largest element and its index, and then remove that element from the array before finding the next largest element. Here's an example:
main.m223 chars5 lines
In this example, we first find the largest element in the array A
using the max
function, which returns both the maximum value and its index. We store these values in the B
and idx
variables, respectively.
We then remove the largest element from the array by indexing into it with idx
and using the empty brackets []
to remove that element.
Finally, we call max
again on the modified A
array to find the next largest element and its index, which we store in C
and idx
.
At this point, B
and C
contain the two largest elements in the array A
.
gistlibby LogSnag