Find the maximum value of a subset of a matrix in MATLAB while maintaining the indices of the full matrix

Currently, I can find the maximum value of matrix C and its index with the following code:

 [max_C, imax] = max(C(:)); [ypeak, xpeak] = ind2sub(size(C),imax(1)); 

Let me call a subset of the matrix C_sub

I want to find the maximum value of C_sub , but also want to know the index of this maximum value in C

It seemed like it should be a mild problem, but it puzzled me.

Thank you for your help!

+6
max matrix indexing matlab subset
source share
5 answers

Suppose C_sub was created

 C_sub = C(rows,cols); 

where rows and cols are index vectors. Save those rows and cols vectors somewhere, you can reuse them if you haven't already.

 [max_C_sub, ind_C_sub] = max(C_sub(:)); [ypeak_sub, xpeak_sub] = ind2sub(size(C_sub), ind_C_sub); xpeak = cols(xpeak_sub); ypeak = rows(ypeak_sub); 

Or, if rows and / or cols was a vector of logical elements instead of an index vector, you can convert them using find and then proceed as described above.

 rows_ind = find(rows_logical); 
+2
source share

If you know the maximum indices in C_sub and know the position of C_sub inside C , you can simply add them (and subtract 1 for Matlab indexing) to get the maximum indices relative to C

+1
source share

I had a similar problem, so I wrote a small utility for this. Find Min2 and Max2 in the file sharing. These tools allow you to specify a subset of the rows and / or columns of a given matrix to search.

Do the same for yourself. Every time you need a tool in MATLAB, write it. Soon you will create a good toolkit of tools tailored to your own special needs. Of course, first look at file sharing, as there is a good chance that what you need has already been written and published there.

+1
source share

What about:

 mask = nan(size(C)); mask(C_sub_indices) = 1; [max_C, imax] = max(C .* mask); 

In this code, C_sub_indices is the index expression applied to C that created C_sub . This code may not work if C_sub not a submatrix of C (for example, if it modifies rows or columns).

0
source share

You can also try this script:

 A=magic(5) [x,y]=find(A==max(max(A))) %index maximum of the matrix A A_max=A(x,y) [x1,y1]=find(A==min(max(A))) %index minimum of the matrix A A_min=A(x1,y1) 
0
source share

All Articles