Louise
Louise

Reputation: 351

MATLAB: Print the indexes alongside an array

I am new to using MATLAB and I have an array of size [131 x 4]. I am looking to locate the row which contains the highest and lowest value in column 2. (my first column is used to label, the next three are used as coordinates)

I want to be able to extract the rows which contain the highest and lowest value in column 2, for example if I knew its index was 5, I would use:

LARGESTX = MYARRAY(5,:)

The MATLAB website gives instructions on how to select particular elements of an array by using indexing, but with my array being so large I can't eyeball the index of the largest/smallest values.

Is there a method which will print the indexes of each row alongside my array? Or to create a new array with the indexes appended on to each row?

Upvotes: 0

Views: 363

Answers (1)

Wolfie
Wolfie

Reputation: 30046

You can use the 2nd outputs of min and max to simply get the indices, there is no need to "eyeball" the correct row from displaying the whole matrix!

[~,minIdx] = min( myarray(:,2) ); % minIdx is the row in column 2 with the min value
[~,maxIdx] = max( myarray(:,2) ); % maxIdx is the row in column 2 with the max value

Then you can index as you suggested

smallestRow = myarray( minIdx, : );
largestRow = myarray( maxIdx, : );

Note I've used a tilde (~) in place of a variable for the first outputs of min and max because I'm not interested in those outputs. The tilde causes the first outputs to be discarded.


Aside from that, the easiest way to do what you've actually asked (display array with row numbers) is to look at the array in the workspace. This will give you a table with row and column numbers.

table

Upvotes: 2

Related Questions