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

To find the index of two largest values of a row of a 2D array in MATLAB, you can first use the max function to find the two largest values of the row, and then use the sort function to sort the values in descending order and return their indices. Here's an example:

main.m
% create a sample 2D array
A = magic(5);

% find the row with the largest values
row = 3;

% find the two largest values of the row
[vals, idx] = max(A(row,:));
[sorted_vals, sorted_idx] = sort(vals, 'descend');

% get the indices of the two largest values
largest_indices = idx(sorted_idx(1:2));
297 chars
13 lines

In this example, we first create a sample 2D array A using the magic function. We then specify that we want to look at row 3 of A. We use the max function to find the two largest values of the row, which returns both the values themselves and their column indices. We then use the sort function to sort the values in descending order and return their indices. Finally, we use indexing to extract the two largest indices from the sorted indices. The resulting largest_indices should contain the indices of the two largest values of the specified row.

related categories

gistlibby LogSnag