find two largest values of a row of a 2d array in matlab

To find the two largest values of a row in a 2D array in Matlab, you can use the sort function along with the 'descend' option to sort the row in descending order, and then take the first two elements of the sorted row:

main.m
A = [1 2 3; 4 5 6; 7 8 9]; % example 2D array
row_index = 2; % index of the row we want to find the largest values for
row = A(row_index, :); % extract the row as a 1D array
sorted_row = sort(row, 'descend'); % sort the row in descending order
largest_values = sorted_row(1:2); % take the first two elements of the sorted row
326 chars
6 lines

This code will give you the two largest values of the second row of the A array, which in this example are 6 and 5, in that order.

related categories

gistlibby LogSnag