find two biggest numbers in array in matlab

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.m
A = [4, 8, 1, 6, 3, 9, 2, 5];
[B, idx] = max(A);   % find the maximum element and its index
A(idx) = [];         % remove the maximum element from the array
[C, idx] = max(A);   % find the new maximum element and its index
223 chars
5 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