find index of 2 largest elements in array in matlab in matlab

To find the indices of the two largest elements in an array in Matlab, you can first use the sort function to sort the array in descending order. Then, you can use the max function to find the two largest elements, and the find function to determine their indices.

Here's an example code snippet:

main.m
% define the input array
A = [1, 5, 3, 8, 2, 9];

% sort the array in descending order
sortedA = sort(A, 'descend');

% find the two largest elements
maxVals = sortedA(1:2);

% find the indices of the two largest elements
idx = find(ismember(A, maxVals));

% display the results
disp(idx);
290 chars
15 lines

This code will output:

main.m
4     6
8 chars
2 lines

which indicates that the 4th and 6th elements of the original array A are the two largest elements.

related categories

gistlibby LogSnag